Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select all node that has certain css-rule without jQuery

How to get all nodes that have certain CSS rule, for example if defined:

html {
  color: blue;
}
div.x {
  color: blue;
}

And I want to get all node that has color: blue, I want to get the html (document.children[0]) and all div with class='x' node only, not all the children that affected by that rule.

EDIT the final target is to remove certain css rule from a website, I've tried this script but doesn't work on Chrome:

var xRules = ['userSelect','webkitTouchCallout','webkitUserSelect','khtmlUserSelect','mozUserSelect','msUserSelect'];
var dS = document.styleSheets;
for(var z in dS) {
  var dsz = dS[z].cssRules;
  if(!dsz) continue;
  for(var y in dsz) {
    var dszy = dsz[y].style;
    if(!dszy) continue;
    console.log(dszy.webkitUserSelect);
    for(var x in xRules) {
      var xx = xRules[x];
      dszy.removeProperty(xx);
    }
  }
}

So all I could think is that I must find the element then remove the styling.

like image 432
Kokizzu Avatar asked Aug 04 '26 19:08

Kokizzu


1 Answers

You could read the loaded css rules using document.styleSheets. Then, find the rules that are setting the specific property, in your case style.color == "blue".

Then, get the selectorText from the rule, it will give you the selectors. It will be easy then to select the elements using document.querySelector() passing the obtained selectors as the parameter.

var classes = document.styleSheets[0].rules || document.styleSheets[0].cssRules;
for (var x = 0; x < classes.length; x++) {
  var cls = classes[x];
  if(cls.style.color == "blue") {
    alert(cls.selectorText);
    
    //Gets a node list of the elements matching the selector
    var elements = document.querySelectorAll(cls.selectorText);
  }
}
html {
  color: blue;
}
div.x {
  color: blue;
}
like image 123
LcSalazar Avatar answered Aug 06 '26 08:08

LcSalazar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!