Thursday, January 29, 2009

[jQuery] Re: Selection by CSS background-color

I'm pretty sure this is going to require using string functions to
locate the background-color property for testing. You could use .css
("background-color") to read in the color attribute, but it will be in
RGB form as shown in the documentation's demo at http://docs.jquery.com/CSS/css#name.

First, let's say you've got your divs within a container like this:
<div id="sitewrapper">
<div style="background-color:red;"></div>
<div style="background-color: firebrick;"></div>
<div style="background-color:green;"></div>
<div style="background-color:darkolivegreen;"></div>
<div style="background-color:firebrick;"></div>
</div>

You could then use this to run through each element and test against
its background-color property.
$(document).ready(function()
{
$("#sitewrapper div").each(function()
{
// Grab your style attribute
bgColor = $(this).attr("style");
// Cut from first instance of background-color: on to end
bgColor = bgColor.substring((bgColor.indexOf("background-color:") +
17));
// Cut remainder of inline styles, if any
bgColor = bgColor.substring(0, (bgColor.indexOf(";")));
// Remove any whitespace
bgColor = bgColor.replace(/ /g, "");
if (bgColor == "firebrick")
{
$(this).text("Match");
}
});
});

No comments: