Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace everytime this color by that color in css with jquery

I have a lot of divs, some of them have a background-color: #aaa, others have font color: #aaa, and others border-color: #aaa. Other divs have different colors, it doesn't matter.

I want to change these colors (#aaa) to #ccc everywhere in the CSS.
I know how to change a background div color but here this is not the problem, I have too many divs to change them one by one.

I'm trying to find a jQuery function which will allow me to find a word (here #aaa) and replace it by with other (#ccc) in the CSS.

It should be like that but my code isn't correct :

$("*").if(backgroundColor == "#aaa"){replace by "#ccc"},
if(color == "#aaa"){replace by "#ccc"}, if(borderColor == "#aaa"){replace by "#ccc"}, etc..
like image 864
user2488028 Avatar asked Jun 15 '13 02:06

user2488028


1 Answers

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/

like image 74
Phillip Berger Avatar answered Oct 18 '22 19:10

Phillip Berger