My suggestion avoids this, if at all possible. Instead, use a class to assign a color value, and then you can search for elements using a class, not a color value.
As far as I know, there is no selector (even in CSS3) that you can use to request a specific style value, which means loop through all elements (or it looks like you can limit it to all elements with a style
) and look at the element.style.color
property element.style.color
. Now, even if you write color: #333;
in its style
attribute, different browsers will send it to you differently. It can be #333
, it can be #333333
, it can be rgb(51, 51, 51)
, it can even be rgba(51, 51, 51, 0)
.
All in all, a very uncomfortable exercise indeed.
Since you said that this is for the Chrome extension, you probably do not need to worry about several formats, although I would choose the ones we saw in the wild in case Chrome changes the format (possibly compatible with some other the browser that is known to have occurred).
But for example:
(function() { // Get all elements that have a style attribute var elms = document.querySelectorAll("*[style]"); // Loop through them Array.prototype.forEach.call(elms, function(elm) { // Get the color value var clr = elm.style.color || ""; // Remove all whitespace, make it all lower case clr = clr.replace(/\s/g, "").toLowerCase(); // Switch on the possible values we know of switch (clr) { case "#333": case "#333333": case "rgb(51,51,51)": // <=== This is the one Chrome seems to use case "rgba(51,51,51,0)": elm.style.color = "#444"; break; } }); })();
Live example using red for clarity | source - Please note that the example is based on ES5 and querySelectorAll
, but since it is Chrome, I know that they are there.
Note that the above assumes an inline style, because you were talking about the style
attribute. If you mean the computed style, then thereβs nothing for it but to scroll the all elements on the page calling getComputedStyle
. In addition, the above applies.
Final note. If you really meant a style attribute with exactly the value color: #333
, and not the value color:#333
or color:#333333;
or color: #333; font-weight: bold
color: #333; font-weight: bold
or any other string, your querySelectorAll
could handle this: querySelectorAll('*[style="color: #333"]')
. But that would be very fragile.
From your comment below, it looks like you need to go through each element. If so, I would not use querySelectorAll
at all, I would use a recursive descent:
function walk(elm) { var node; // ...handle this element `style` or `getComputedStyle`... // Handle child elements for (node = elm.firstChild; node; node = node.nextSibling) { if (node.nodeType === 1) { // 1 == Element walk(node); } } } // Kick it off starting with the `body` element walk(document.body);
This way you are not creating large, unnecessary temporary structures. This is perhaps the most efficient way to move an entire DOM document.