12

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..
user2488028
  • 131
  • 1
  • 1
  • 6

1 Answers1

5

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/

Phillip Berger
  • 2,317
  • 1
  • 11
  • 30
  • But this code will change div which don't have color #aaa at the beggining ! Imagine div 1 and div 2 have color #aaa but div 3 and div 4 have color #888, I only want to change div 1 and 2 to #ccc, but i want #888 to stay #888. This is why I have to check the color of div at the beggining. – user2488028 Jun 15 '13 at 03:33
  • When I said "All in the page" i tried to say "All div which have #aaa color in the page" but not "All div in the page". – user2488028 Jun 15 '13 at 03:45
  • It seems to be good, but it's not finished. I don't only want to check div but ul, li, img, a, etc... Can i do $("div,ul,li,a,img,...").each(function () {...}}); ? And after that I try to find not only color but backgroundcolor or border color in div, ul, li,etc .. Thank you – user2488028 Jun 15 '13 at 04:21
  • Yes, you can plugin whatever element you want for `div`. I just used `div` as an example. – Phillip Berger Jun 16 '13 at 04:47
  • using $("*") instead of $("div") will allow searching of all elements on the page. – Alan Dyke Aug 13 '19 at 20:19