Alban
Alban

Reputation: 31

Update or remove css rule from insertRule() in JS

I have inserted a rule (with a for) with the following :

document.styleSheets[0].insertRule(`#li${i}:after {content: "${data[2][i]}"; }`, 0);

How can I update or remove it ?

Why ? : Because if I run my for loop a second time with new data it won't update the content of the hover (I need it in here : https://vengeur69.github.io/public/Wikipedia_api/)

Example :

I get data with the term "yes"

I get data with the term "no" but the content didn't change

Thank you

Upvotes: 2

Views: 3579

Answers (1)

Patrick Evans
Patrick Evans

Reputation: 42746

To delete just use deleteRule() passing in the index that the rule was inserted at

var index = document.styleSheets[0].insertRule(`#li${i}:after {content: "${data[2][i]}"; }`, 0);
document.styleSheets[0].deleteRule(index);

In order to update a rule access the cssRules list at the index the rule was inserted at, and change the style property

document.styleSheets[0].cssRules[index].style.content = "";

Note you will not be able to access the rule if the style sheet being accessed was linked externally as cssRules will be null. So you will have to delete it and insert it back to change its styles.

Demo

var stylesheet = document.styleSheets[0];
var ruleIndex = 0;

function redRule(){
  stylesheet.cssRules[ruleIndex].style.color = "red";
}

function blueRule(){
  stylesheet.cssRules[ruleIndex].style.color = "blue";
}

function replaceRule(){
  stylesheet.deleteRule(ruleIndex);
  ruleIndex = stylesheet.insertRule("body { color:yellow; }",0);    
}

ruleIndex = stylesheet.insertRule("body { color:black; }",0);

document.addEventListener('click',function(e){
 switch(e.target.id){
   case 'red':
     redRule();
     break;
   case 'blue':
     blueRule();
     break;
   case 'replace':
     replaceRule();
     break;
 }
});
<style></style>
Text<br>
<button id="red">Change rule to red</button><br>
<button id="blue">Change rule to blue</button><br>
<button id="replace">Replace rule</button><br>

Upvotes: 5

Related Questions