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.

1.21 gigawatts
  • 16,517
  • 32
  • 123
  • 231

4 Answers4

3

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);
1.21 gigawatts
  • 16,517
  • 32
  • 123
  • 231
Amir
  • 232
  • 3
  • 11
  • 1
    While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/low-quality-posts/15350927) – Shadow Feb 27 '17 at 06:10
  • Thanks @Shadow, this is a much better feedback than "No, no, no, ...". – Amir Feb 27 '17 at 06:12
  • @torazaburo, Did I say it's a good practice? NO. Did I answer the question? YES. – Amir Feb 27 '17 at 06:42
  • thanks @gigawatts, hope it helped, btw I agree that it's probably best if you follow better patterns like adding or removing classes. – Amir Feb 27 '17 at 06:45
  • I did not vote you down. – Shadow Feb 27 '17 at 06:57
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');
Darshak
  • 859
  • 7
  • 18
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.

Ouroborus
  • 16,237
  • 4
  • 39
  • 62
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);
JeremiahB
  • 896
  • 8
  • 15