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
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>
Using CSS Selectors is another vital way .
visit this link http://www.w3schools.com/cssref/css_selectors.asp
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With