I have a lot of div
s, some of them have a background-color: #aaa
, others have font color: #aaa
, and others border-color: #aaa
You want to iterate over all the elements of the type you want (in this case I picked div
since it’s super common) and assign the color dynamically like so:
HTML:
<div id="one">Some text</div>
<div id="two">Some text</div>
<div id="three">Some text</div>
<div id="four">Some text</div>
<div id="change">
<input type="button" value="Change Colors!" />
</div>
JQuery:
$("#change").click(function () {
$("div").each(function () {
var color = $(this).css("color");
if (color == "rgb(170, 170, 170)") {
$(this).css("color", "#ccc");
}
});
});
NOTE: JQuery .css()
returns an RGB color value like rgb(r, g, b) so you need to convert the returned RGB value to a HEX value. This can be done programatically but is outside the scope of this question.
CSS:
#one, #two {
color: #aaa;
}
#three, #four {
color: green;
}
Here is the JSFiddle:
http://jsfiddle.net/hQkk3/44/