Sampisa
Sampisa

Reputation: 1603

How to change style of a class without JQuery

Suppose to have about 2000 elements in a page like

<div class="good">fruit</div>
<div class="bad">stone</div>
<div class="bad">sand</div>
<div class="good">water</div>
<div class="good">carrot</div>

and style is

.good { color: green }
.bad  { color: red }

I want to change css "color" value of classes "good" and "bad" without iterate getElementsByClassName. E.g. something like (invented)

document.class["good"].style.color="yellow"

I didn't find any way to change class definition in order to let all tags marked with that class change style: do it exists? Is it possible?

MANDATORY: I {don't want, can't} use jQuery.

EDIT: I need to do it via Javascript, or find a way to change a attribute of whole class so that whole page is affected by change at the same time (I repeat, without iteration over document.getElementsByClassName("good")). I mean, I don't want use getElementsByClassName. I want that style element "color" is changed for class "good" so that "good" class has color "yellow" instead than "green". I don't want to change style of elements of document with that class, I want to change style of class. Is it possible? Thank you

Upvotes: 7

Views: 13912

Answers (3)

Nenad Vracar
Nenad Vracar

Reputation: 122115

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 }
<div class="good">fruit</div>
<div class="bad">stone</div>
<div class="bad">sand</div>
<div class="good">water</div>
<div class="good">carrot</div>

Upvotes: 3

Mohammed Elhag
Mohammed Elhag

Reputation: 4302

Using CSS Selectors is another vital way .

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

Upvotes: 1

felipecamposclarke
felipecamposclarke

Reputation: 924

I think this is what you want

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

Upvotes: 0

Related Questions