0

Is there a way to add and remove or disable a CSS rule in JavaScript? Here is the CSS:

#myElement *, #myElement *:before {
   outline:1px dotted red;
}

Here is what I have so far:

var myCSS = "#myElement *, #myElement *:before {outline:1px dotted red;}";
// document.addCSS(myCSS);

EDIT:
I can't add the rules to the HTML page and toggle between them. I need to be able to create a rule in JavaScript after the page loads and also switch it on and off in JS.

3
  • 2
    your question is not clear.What is is the expected output? Commented Feb 27, 2017 at 5:33
  • My question is different than the one linked in that I must also be able to remove the rule (or disable it). Commented Feb 27, 2017 at 6:48
  • My question is different than the one marked as duplicate. My question asks how to remove or disable. The linked question does not provide that information. Commented Feb 27, 2017 at 10:06

4 Answers 4

4

Seems like you could find an answer here on Mozilla Developer Network:

https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet/insertRule

Inserts a new CSS rule into the current style sheet

Example:

// create a style sheet and add rule
var borderStyleSheet = document.createElement("style");
document.head.appendChild(borderStyleSheet);
borderStyleSheet.sheet.insertRule("#myElement *{ outline: 1px solid red;}", 0);

// disable rule
borderStyleSheet.disabled = true;

// enable rule
borderStyleSheet.disabled = false;

// see existing stylesheets
console.log(document.styleSheets);
Sign up to request clarification or add additional context in comments.

Comments

2

You Can add class using className property

document.getElementById("myElement").className += " MyClass";

you can add multiple class and remove class using classList

 document.getElementById("myElement").classList.add('newclass');

 document.getElementById("myElement").classList.remove('newclass');

2 Comments

The OP's question is how to turn the rule on or off.
@torazaburo :- he say remove later using any javascript condition...its not say toggling functionality right??
1

The common way of doing this is to use a class to turn on/off the styles. As in:

#myElement.outline *, #myElement.outline *:before {
  outline:1px dotted red;
}

Then (in this example) you add/remove the outline class as needed via javascript.

Comments

1

You can do so as follows:

var sheet = document.styleSheets[0];
sheet.insertRule(".foo { color:pink; }", sheet.cssRules.length);

Except on internet explorer <= 8, where you must write

sheet.addRule(".foo", "color: pink;", -1);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.