Generally, when I'm not using JQuery, I use the following utility function to get properties from a stylesheet using Javascript. This works nicely to get values from CSS style sheets:
<!DOCTYPE html>
<html>
<head>
<style>
.foo {
color: red;
}
</style>
<script type = "text/javascript">
function getcss(selector, property)
{
var len = document.styleSheets.length;
for (var idx = 0; idx < len; ++idx)
{
var sheet = document.styleSheets && document.styleSheets[idx];
if (sheet)
{
var r = sheet.rules ? sheet.rules : sheet.cssRules;
if (r)
{
var i = r.length;
while (i--)
{
if (r[i].selectorText && r[i].selectorText.toLowerCase() === selector.toLowerCase())
{
return (r[i].style[property]);
}
}
}
}
}
return null;
}
function exec()
{
alert(getcss(".foo", "color"));
}
</script>
</head>
<body onload = "exec()">
</body>
</html>
The problem is that it doesn't take into account media queries. If I replace the <style> section of the above code with:
.foo {
color: red;
}
#media screen and (max-width: 600px) {
.foo {
color: green;
}
}
...it still outputs red if I shrink the window to smaller than 600px.
Is this correct WC3 behavior? Or is this a browser bug? (I'm testing with Firefox 12 on Ubuntu).
Is there anyway to correct this, so that Javascript "sees" the correct style sheet as required by the media query?
Your code is simply looking through the rules of a stylesheet, and only the first list of rules at that. The rules are a object representation of the stylesheet -- they don't change just because you've resized your browser.
In your code you're never going to see the green rul because you're only iterating over the items in the first CSSRuleList. The trick here is you need to recursively loop over any additional rules that are CSSMediaRule and contain their own CSSRuleList. For you, the sheet.rules contains both a single CSSSyleRule (which is your .foo { color:red; }) and a CSSMediaRule (which is your media query). That second rule then its own CSSRuleList, which you can traverse to find your green color.
In this case, here's where your data lies:
// Assuming sheet 0 is your stylesheet above
var sheet = document.styleSheets[0];
// First rule is ".foo { color: red; }"
console.log(sheet.cssRules[0].cssText);
// Second Rule is your "#media" and its first rule is ".foo { color: green; }"
console.log(sheet.cssRules[1].cssRules[0].cssText);
Related
I made a function that overwrite the the :hover of some elements on a page. It fades between the normal and the :hover effect. That for i had to create a .hover class in my CSS file. I think this is a little unclean. How could i read the the :hover pseudo class contents?
Using getComputedStyle as on the accepted answer won't work, because:
The computed style for the hover state is only available when the element is actually on that state.
The second parameter to getComputedStyle should be empty or a pseudo-element. It doesn't work with :hover because it's a pseudo-class.
Here is an alternative solution:
function getCssPropertyForRule(rule, prop) {
var sheets = document.styleSheets;
var slen = sheets.length;
for(var i=0; i<slen; i++) {
var rules = document.styleSheets[i].cssRules;
var rlen = rules.length;
for(var j=0; j<rlen; j++) {
if(rules[j].selectorText == rule) {
return rules[j].style[prop];
}
}
}
}
// Get the "color" value defined on a "div:hover" rule,
// and output it to the console
console.log(getCssPropertyForRule('div:hover', 'color'));
Demo
You could access document.styleSheets and look for a rule that is applied on that specific element. But that’s not any cleaner than using a simple additional class.
UPDATE: I somehow got this wrong. The below example doesn't work. See #bfavaretto's comment for an explanation.
In Firefox, Opera and Chrome or any other browser that correctly implements window.getComputedStyle is very simple. You just have to pass "hover" as the second argument:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style type="text/css">
div {
display: block;
width: 200px;
height: 200px;
background: red;
}
div:hover {
background: green;
}
</style>
</head>
<body>
<div></div>
<script type="text/javascript">
window.onload = function () {
var div = document.getElementsByTagName("div")[0];
var style = window.getComputedStyle(div, "hover");
alert(style.backgroundColor);
};
</script>
</body>
</html>
But I don't believe there's yet a solution for Internet Explorer, except for using document.styleSheets as Gumbo suggested. But there will be differences. So, having a .hover class is the best solution so far. Not unclean at all.
If there are any people here who use the questions accepted answer but it won't work, here's a nice function that might:
function getPseudoStyle(id, style) {
var all = document.getElementsByTagName("*");
for (var i=0, max=all.length; i < max; i++) {
var targetrule = "";
if (all[i].id === id) {
if(all[i].selectorText.toLowerCase()== id + ":" + style) { //example. find "a:hover" rule
targetrule=myrules[i]
}
}
return targetrule;
}
}
There is an alterantive way to get :hover pseudo class with javascript. You can write your styles of hover pseudo class in a content property.
p::before,
p::after{
content: 'background-color: blue; color:blue; font-size: 14px;';
}
then read from it via getComputedStyle() method:
console.log(getComputedStyle(document.querySelector('p'),':before').getPropertyValue('content'));
I'm trying to implement a dark mode that activates according to the current time.
That's how I change the body's background color:
if (darkMode) {
document.body.style.backgroundColor = '#31403E';
} else {
document.body.style.backgroundColor = '#F2EDE4';
}
Can I change the h1 tag's color in some kind of global way? Or do I have to check for the property darkMode in every single doc and then assign the proper color.
In modern JavaScript, it could be:
const elements = document.querySelectorAll('h1')
Array.from(elements).forEach(el => el.style.color = '#31403E')
Hope this helps.
You can define a custom CSS stylesheet for dark mode:
#media (prefers-color-scheme: dark) {
color: white;
background: black
}
Where you can define your custom rules accordingly.
There's a nice trick about using filter as well that you can read a bit further over here
You can see this example over here:
https://codepen.io/rikschennink/pen/GLMLj
Where a class .dark-mode is set to the HTML document when toggling using
html.dark-mode {
filter: invert(100%);
img {
filter: invert(100%);
}
}
Docs
first of all they added dark mode preferences in css, they work like so:
#media (prefers-color-scheme: dark) {
h1 {
color: white;
}
}
but a common workaround to this back when we were developing theme switches was adding a "dark" class to the body and doing the following in css
body.dark h1 {
color: white;
}
IF YOU HAVE TO DO IT WITH JAVASCRIPT you have to loop through each and every h1's in the DOM, but it wont work on newly made h1s using javascript since it'll run on page load only as is.
let h1s = document.querySelectorAll("h1"); //gets all the h1s in the page
h1s.forEach( h1 => h1.style.color = "white");
With javascript you can do it like this:
var elements = document.getElementsByTagName("h1");
for(var i = 0; i < elements.length; i++) {
elements[i].style.color = "#000";
}
How could I remove media query loaded from external css file (<link rel="stylesheet" type="text/css" href="XXXX.css" media="screen">)? Note that I cant disable the entire link tag because other important styles are included out of that media query:
body{...}
.container{...}
...
#media(min-width:XXXpx) {
....
}
...
Thank you!
I strongly recommend pure CSS solution for this problem, such as defining a new stylesheet overwritting rules you don't want.
#selector {
color: #000;
}
.some-classs-you-want-to-reserve {/*..*/}
#media only screen and (min-width: 600px) {
/* unwanted */
#selector {
display: none;
}
}
For example, if you want to mute rules inside #media only screen and (min-width: 600px), simply add a new stylesheet overwritting them to default values:
#media only screen and (min-width: 600px) {
/* unwanted */
#selector {
display: block;
}
}
If you insist on using Javascript, you can access and modify css rules by iterating document.styleSheets.
https://developer.mozilla.org/en-US/docs/Web/API/StyleSheetList
https://developer.mozilla.org/en-US/docs/Web/API/document.styleSheets
This is an instance of StyleSheetList, an array-like object. Each item of it represents an external or inline css stylesheet. All rules including media queries can be found inside it.
A brief tree structure:
- document.styleSheets
|- CSSStyleSheet
|- cssRules
|- media
So here's an example showing how to remove all rules defined inside #media only screen and (min-width: 600px) block:
function removeRule() {
if(typeof window.CSSMediaRule !== "function")
return false; //Your browser doesn't support media query feature
var s = document.styleSheets, r,
i, j, k;
if(!s) return false; //no style sheets found
// walk throuth css sheets
for(i=0; i<s.length; i++) {
// get all rules
r = s[i].cssRules;
if(!r) continue;
for(j=0; j<r.length; j++) {
//If there's a rule for media query
if(r[j] instanceof CSSMediaRule &&
r[j].media.mediaText == "only screen and (min-width: 600px)") {
for(k=0; k<r[j].cssRules.length; k++) {
// remove all rules of it
r[j].deleteRule(r[j].cssRules[k]);
}
return true;
}
}
}
}
removeRule();
Or live fiddle: http://jsfiddle.net/e4h41qm2/
The fact is, if you delete one media query, another one get's activated. So you have to do a loop till no media query is found:
function removeRule() {
if (typeof window.CSSMediaRule !== 'function') {
return false;
}
var styleSheets = document.styleSheets;
var number = 0;
if (!styleSheets) {
return false;
}
for (i = 0; i < styleSheets.length; i++) {
var styleSheet = styleSheets[i];
var rules = styleSheet.cssRules;
if (!rules) {
continue;
}
for (var j = 0; j < rules.length; j++) {
var cssText = rules[j].cssText;
if (cssText.indexOf('#media') === 0) {
number++;
styleSheet.deleteRule(j);
}
}
}
if (number) {
return number;
}
return 0;
}
function removeMediaQueries() {
var num = removeRule();
var total = num;
while (num) {
num = removeRule();
total += num;
}
if (total) {
console.info(total + ' media quer' + (total == 1 ? 'y' : 'ies' + ' removed'));
} else {
console.info('No media queries removed');
}
}
removeMediaQueries();
If you put all this in one line you can generate a bookmark in your browser and have a fast way to test the design without media queries. Very useful for newsletter.
javascript:!function(){function e(){if("function"!=typeof window.CSSMediaRule)return!1;var e=document.styleSheets,n=0;if(!e)return!1;for(i=0;i<e.length;i++){var o=e[i],r=o.cssRules;if(r)for(var t=0;t<r.length;t++){var f=r[t].cssText;0===f.indexOf("#media")&&(n++,o.deleteRule(t))}}return n?n:0}function n(){for(var i=e(),n=i;i;)i=e(),n+=i;n?console.info(n+" media quer"+(1==n?"y":"ies removed")):console.info("No media queries removed")}n()}();
You're probably better off overriding it instead of trying to delete it, but if you must:
style = document.styleSheets[0]; // or whatever stylesheet you want
[].forEach.call(style.cssRules || [], function(rule, i) {
if (!rule.cssText.indexOf('#media(min-width:XXXpx') {
style.deleteRule(i);
}
});
Untested.
I've been using a number of libraries (including my own) to dynamically load assets based upon media queries I've outlined in CSS files. For example:
In CSS:
#media screen and (max-width: 480px) {
.foo {
display: none;
}
}
And using an asset loader; require.js, modernizr.js etc or using window.matchMedia and associated addListener() functions:
if (function("screen and (max-width: 480px)")){
// Load several files
load(['mobile.js','mobile.css']);
}
Declaring them twice is awkward/silly and as far as I can find, all JS helper libraries and asset loaders require you to repeat the media queries rather than locating them programmatically from JS/DOM.
So, I've been exploring the ability to access the values programmatically via document.stylesheets, but I'm not sure if they're accessible and there seems very little documentation to suggest they are.
The furthest I've got is looking for CSSMediaRule and using console.dir(document.stylesheets) amongst others to explore the stylesheet object.
But no references are made (within document.stylesheets) to the actual media query rules used in CSS - only the classes to be applied as a result of the media queries... What I'm trying to locate, programmatically, is:
"screen and (max-width: 480px)"
Is there any way of accessing such CSS Media query rules via JavaScript/DOM?
For get rules use cross browser variant:
var styleSheet = document.styleSheets[0];
var rules = styleSheet.cssRules || styleSheet.rules; // IE <= 8 use "rules" property
For detect CSSMediaRule object in rules list use (not work in IE <= 8, because "CSSMediaRule" class available only in IE >= 9):
var i = 0;
if (rules[i].type == 4)
{
// Do something
}
Some functions for get styles from current DOM (not works in IE <= 8):
function getCssRulesFromDocumentStyleSheets(media)
{
var resultCssRules = '';
for (var i = 0; i < document.styleSheets.length; i++)
{
var styleSheet = document.styleSheets[i];
if (isRuleFromMedia(styleSheet, media))
resultCssRules += getCssRulesFromRuleList(styleSheet.cssRules || styleSheet.rules, media);
}
return resultCssRules;
}
function getCssRulesFromRuleList(rules, media)
{
var resultCssRules = '';
for (var i = 0; i < rules.length; i++)
{
var rule = rules[i];
if (rule.type == 1) // CSSStyleRule
{
resultCssRules += rule.cssText + "\r\n";
}
else if (rule.type == 3) // CSSImportRule
{
if (isRuleFromMedia(rule, media))
resultCssRules += getCssRulesFromRuleList(rule.styleSheet.cssRules || rule.styleSheet.rules, media);
}
else if (rule.type == 4) // CSSMediaRule
{
if (isRuleFromMedia(rule, media))
resultCssRules += getCssRulesFromRuleList(rule.cssRules || rule.rules, media);
}
}
return resultCssRules;
}
function isRuleFromMedia(ruleOrStyleSheet, media)
{
while (ruleOrStyleSheet)
{
var mediaList = ruleOrStyleSheet.media;
if (mediaList)
{
if (!isMediaListContainsValue(mediaList, media) && !isMediaListContainsValue(mediaList, 'all') && mediaList.length > 0)
return false;
}
ruleOrStyleSheet = ruleOrStyleSheet.ownerRule || ruleOrStyleSheet.parentRule || ruleOrStyleSheet.parentStyleSheet;
}
return true;
}
function isMediaListContainsValue(mediaList, media)
{
media = String(media).toLowerCase();
for (var i = 0; i < mediaList.length; i++)
{
// Access to mediaList by "[index]" notation now work in IE (tested in versions 7, 8, 9)
if (String(mediaList.item(i)).toLowerCase() == media)
return true;
}
return false;
}
Functions usage example:
<style type="text/css">
#media screen and (max-width: 480px) {
p { margin: 10px; }
}
#media screen and (max-width: 500px) {
p { margin: 15px; }
}
#media print {
p { margin: 20px; }
}
</style>
<!-- ... -->
<script type="text/javascript">
alert(getCssRulesFromDocumentStyleSheets('print'));
alert(getCssRulesFromDocumentStyleSheets('screen and (max-width: 480px)'));
// For IE (no space after colon), you can add fix to "isMediaListContainsValue" function
alert(getCssRulesFromDocumentStyleSheets('screen and (max-width:480px)'));
</script>
Here is a JS Fiddle for it: https://jsfiddle.net/luisperezphd/hyentcqc/
This is how I do it:
In css create classes to expose or hide content at various breakpoints.
This is a handy utility anyway. These are already available in Twitter Bootstrap for example.
<style type="text/css">
.visible-sm, .visible-md, .visible-lg{
display:none;
}
#media (max-width: 480px) {
.visible-sm{
display: block;
}
}
#media (min-width: 481px) and (max-width: 960px) {
.visible-md{
display: block;
}
}
#media (min-width: 961px) {
.visible-lg{
display: block;
}
}
</style>
In all your documents add empty spans with these classes.
They won't show up on the page if you keep the spans inline.
<span id="media_test">
<span class="visible-sm"></span>
<span class="visible-md"></span>
<span class="visible-lg"></span>
</span>
Add this short jquery extension to your script file.
This sets a new class in the body tag that matches the current media query.
(function ($) {
$.fn.media_size = function () {
//the default port size
var size = 'lg';
//the sizes used in the css
var sizes = ['sm','md','lg'];
//loop over to find which is not hidden
for (var i = sizes.length - 1; i >= 0; i--) {
if($('#media_test .visible-'+sizes[i]).css("display").indexOf('none') == -1){
size = sizes[i];
break;
};
};
//add a new class to the body tag
$('body').removeClass(sizes.join(' ')).addClass(size);
}
}(jQuery));
$(document).media_size();
Now you have an automatic integration with your css media queries Modernizr style.
You can write javascript (jquery) that is conditional on based on your media queries:
how big is this viewport?
<script type="text/javascript">
$('.sm a').click(function(e){ alert('Media queries say I\'m a small viewport');});
$('.lg a').click(function(e){ alert('Media queries say I\'m a large viewport');});
</script>
How do you add CSS rules (eg strong { color: red }) by use of Javascript?
The simple-and-direct approach is to create and add a new style node to the document.
// Your CSS as text
var styles = `
.qwebirc-qui .ircwindow div {
font-family: Georgia,Cambria,"Times New Roman",Times,serif;
margin: 26px auto 0 auto;
max-width: 650px;
}
.qwebirc-qui .lines {
font-size: 18px;
line-height: 1.58;
letter-spacing: -.004em;
}
.qwebirc-qui .nicklist a {
margin: 6px;
}
`
var styleSheet = document.createElement("style")
styleSheet.innerText = styles
document.head.appendChild(styleSheet)
You can also do this using DOM Level 2 CSS interfaces (MDN):
var sheet = window.document.styleSheets[0];
sheet.insertRule('strong { color: red; }', sheet.cssRules.length);
...on all but (naturally) IE8 and prior, which uses its own marginally-different wording:
sheet.addRule('strong', 'color: red;', -1);
There is a theoretical advantage in this compared to the createElement-set-innerHTML method, in that you don't have to worry about putting special HTML characters in the innerHTML, but in practice style elements are CDATA in legacy HTML, and ‘<’ and ‘&’ are rarely used in stylesheets anyway.
You do need a stylesheet in place before you can started appending to it like this. That can be any existing active stylesheet: external, embedded or empty, it doesn't matter. If there isn't one, the only standard way to create it at the moment is with createElement.
Shortest One Liner
// One liner function:
const addCSS = css => document.head.appendChild(document.createElement("style")).innerHTML=css;
// Usage:
addCSS("body{ background:red; }")
The solution by Ben Blank wouldn't work in IE8 for me.
However this did work in IE8
function addCss(cssCode) {
var styleElement = document.createElement("style");
styleElement.type = "text/css";
if (styleElement.styleSheet) {
styleElement.styleSheet.cssText = cssCode;
} else {
styleElement.appendChild(document.createTextNode(cssCode));
}
document.getElementsByTagName("head")[0].appendChild(styleElement);
}
Here's a slightly updated version of Chris Herring's solution, taking into account that you can use innerHTML as well instead of a creating a new text node:
function insertCss( code ) {
var style = document.createElement('style');
style.type = 'text/css';
if (style.styleSheet) {
// IE
style.styleSheet.cssText = code;
} else {
// Other browsers
style.innerHTML = code;
}
document.getElementsByTagName("head")[0].appendChild( style );
}
You can add classes or style attributes on an element by element basis.
For example:
<a name="myelement" onclick="this.style.color='#FF0';">text</a>
Where you could do this.style.background, this.style.font-size, etc. You can also apply a style using this same method ala
this.className='classname';
If you want to do this in a javascript function, you can use getElementByID rather than 'this'.
This easy example of add <style> in head of html
var sheet = document.createElement('style');
sheet.innerHTML = "table th{padding-bottom: 0 !important;padding-top: 0 !important;}\n"
+ "table ul { margin-top: 0 !important; margin-bottom: 0 !important;}\n"
+ "table td{padding-bottom: 0 !important;padding-top: 0 !important;}\n"
+ ".messages.error{display:none !important;}\n"
+ ".messages.status{display:none !important;} ";
document.body.appendChild(sheet); // append in body
document.head.appendChild(sheet); // append in head
Source Dynamic style - manipulating CSS with JavaScript
This is my solution to add a css rule at the end of the last style sheet list:
var css = new function()
{
function addStyleSheet()
{
let head = document.head;
let style = document.createElement("style");
head.appendChild(style);
}
this.insert = function(rule)
{
if(document.styleSheets.length == 0) { addStyleSheet(); }
let sheet = document.styleSheets[document.styleSheets.length - 1];
let rules = sheet.rules;
sheet.insertRule(rule, rules.length);
}
}
css.insert("body { background-color: red }");
YUI just recently added a utility specifically for this. See stylesheet.js here.
In modern browsers, you can use document.adoptedStyleSheets to add CSS.
const sheet = new CSSStyleSheet();
sheet.replace("strong { color: red; }");
document.adoptedStyleSheets = [...document.adoptedStyleSheets, sheet];
One advantage of this approach is that you do not have to wait for the <head> element to even become available, which may be a concern in browser extension code that runs very early.
if you know at least one <style> tag exist in page , use this function :
CSS=function(i){document.getElementsByTagName('style')[0].innerHTML+=i};
usage :
CSS("div{background:#00F}");
Another option is to use JQuery to store the element's in-line style property, append to it, and to then update the element's style property with the new values. As follows:
function appendCSSToElement(element, CssProperties)
{
var existingCSS = $(element).attr("style");
if(existingCSS == undefined) existingCSS = "";
$.each(CssProperties, function(key,value)
{
existingCSS += " " + key + ": " + value + ";";
});
$(element).attr("style", existingCSS);
return $(element);
}
And then execute it with the new CSS attributes as an object.
appendCSSToElement("#ElementID", { "color": "white", "background-color": "green", "font-weight": "bold" });
This may not necessarily be the most efficient method (I'm open to suggestions on how to improve this. :) ), but it definitely works.
Here's a sample template to help you get started
Requires 0 libraries and uses only javascript to inject both HTML and CSS.
The function was borrowed from the user #Husky above
Useful if you want to run a tampermonkey script and wanted to add a toggle overlay on a website (e.g. a note app for instance)
// INJECTING THE HTML
document.querySelector('body').innerHTML += '<div id="injection">Hello World</div>';
// CSS INJECTION FUNCTION
//https://stackoverflow.com/questions/707565/how-do-you-add-css-with-javascript
function insertCss( code ) {
var style = document.createElement('style');
style.type = 'text/css';
if (style.styleSheet) {
// IE
style.styleSheet.cssText = code;
} else {
// Other browsers
style.innerHTML = code;
}
document.getElementsByTagName("head")[0].appendChild( style );
}
// INJECT THE CSS INTO FUNCTION
// Write the css as you normally would... but treat it as strings and concatenate for multilines
insertCss(
"#injection {color :red; font-size: 30px;}" +
"body {background-color: lightblue;}"
)
Here's my general-purpose function which parametrizes the CSS selector and rules, and optionally takes in a css filename (case-sensitive) if you wish to add to a particular sheet instead (otherwise, if you don't provide a CSS filename, it will create a new style element and append it to the existing head. It will make at most one new style element and re-use it on future function calls). Works with FF, Chrome, and IE9+ (maybe earlier too, untested).
function addCssRules(selector, rules, /*Optional*/ sheetName) {
// We want the last sheet so that rules are not overridden.
var styleSheet = document.styleSheets[document.styleSheets.length - 1];
if (sheetName) {
for (var i in document.styleSheets) {
if (document.styleSheets[i].href && document.styleSheets[i].href.indexOf(sheetName) > -1) {
styleSheet = document.styleSheets[i];
break;
}
}
}
if (typeof styleSheet === 'undefined' || styleSheet === null) {
var styleElement = document.createElement("style");
styleElement.type = "text/css";
document.head.appendChild(styleElement);
styleSheet = styleElement.sheet;
}
if (styleSheet) {
if (styleSheet.insertRule)
styleSheet.insertRule(selector + ' {' + rules + '}', styleSheet.cssRules.length);
else if (styleSheet.addRule)
styleSheet.addRule(selector, rules);
}
}
I always forget how to add a class to an HTML element and this SO comes up early in Google, but no one has added the modern way of doing this so here goes.
To add a CSS style you can select the element and call .classList.add(<className>)
for example:
document.querySelector("#main").classList.add("bg-primary");
You may also need to remove other class(es) which clash with the one you add. To do so:
document.querySelector("#main").classList.remove("bg-secondary");
That's it. Run the sample and you'll see the setInterval() method add & remove the styles every 3 seconds.
let useSecondary = false;
setInterval(changeBgColor, 3000);
function changeBgColor(){
if (useSecondary){
document.querySelector("#main").classList.remove("bg-primary");
document.querySelector("#main").classList.add("bg-secondary");
}
else{
document.querySelector("#main").classList.remove("bg-secondary");
document.querySelector("#main").classList.add("bg-primary");
}
useSecondary = !useSecondary;
}
* {
transition: all 0.5s ease-in-out;
}
.bg-primary {
background-color: green;
}
.bg-secondary{
background-color: yellow;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div >
<div id="main" >
Example text has background color changed every 3 seconds by adding / removing CSS styles.
</div>
</div>
</body>
</html>
use .css in Jquery like $('strong').css('background','red');
$('strong').css('background','red');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<strong> Example
</strong>