Skip to content Skip to sidebar Skip to footer

How To Change Style Of A Class Without Jquery

Suppose to have about 2000 elements in a page like
fruit
stone
sand

Solution 1:

You can use getElementsByClassName() but then you must to loop HTMLCollection DEMO

var good = document.getElementsByClassName('good');
for (var i = 0; i < good.length; i++) {
  good[i].style.color = 'yellow';
}

Update: You can change css class with Document.styleSheets and this is how. Note: You need to find correct number of your css file, in this demo its [0]

var changeStyle = function(selector, prop, value) {
  var style = document.styleSheets[0].cssRules || document.styleSheets[0].rules;
  for (var i = 0; i < style.length; i++) {
    if (style[i].selectorText == selector) {
      style[i].style[prop] = value;
    }
  }
}

changeStyle('.good', 'color', 'purple');
changeStyle('.bad', 'color', 'yellow');
.good { color: green }
.bad  { color: red }
<divclass="good">fruit</div><divclass="bad">stone</div><divclass="bad">sand</div><divclass="good">water</div><divclass="good">carrot</div>

Solution 2:

Using CSS Selectors is another vital way .

visit this link http://www.w3schools.com/cssref/css_selectors.asp

Solution 3:

I think this is what you want

elements = document.getElementsByClassName("god");
for(i=0; i<elements.length; i++) {
  elements[i].className += " bad";
}

Post a Comment for "How To Change Style Of A Class Without Jquery"