20

I would like to select every div that has a red background color for example. is this possible in jquery?

<div style="background-color:red"></div>
<div style="background-color:white"></div>
<div style="background-color:red"></div>
<div style="background-color:yellow"></div>

thank you

6 Answers 6

24

This code also works for CSS that is not defined in the style attribute of the tag:

$('div').filter(function() {
   return $(this).css('background-color') == 'red';
});
Sign up to request clarification or add additional context in comments.

Comments

21

You could use the jQuery filter:

$('div').filter(function() {
   return this.element.style['background-color'] == 'red';
});

But, as tvanfosson has said, the correct way would be to assign a CSS class to each of your divs, then you could call the objects using jQuery like this (which is the preferred way of working with jQuery):

$('.yourCSSClass');

2 Comments

That would only work if the background color is explicitly declared in the style attribute of the tag...
return this.style['background-color'] == 'red'; - this worked for me
18
$('div[style=background-color:red]');

4 Comments

@ThiefMaster - I answered the question in reference to the example html above.
nothing wrong with that, just worth pointing out in case someone using this doesn't realize that. Also, if the style tag isn't formatting exactly like background-color:red this will not match
this doesn't really work if the color is specified in hex: #AABBCC, probably because of the #. How can we escape the # ?
answered my own comment: you need double backslash for escaping, and the colon (:) should also be escaped: jQuery('div[style=color\\:\\#AABBCC]
7

Why do it the hard way? A better solution is to use CSS classes to give your elements their styles, then you can simply use the class-based selector.

<style type="text/css">
    .alert {
       background-color: red;
    }
</style>

<div class="alert"></div>


$('.alert')....

Comments

3

First of all, I never recommend setting in-line styles on page elements. Assign CSS classes and control your background colors in an external CSS document.

<div class="red"></div>
<div class="white"></div>
<div class="red"></div>
<div class="yellow"></div>

And in your CSS:

.red {background-color:red;}
.white {background-color:white;}
.yellow {background-color:yellow;}

Then it makes it easy to select the red ones by using: $('div.red')

Comments

2

I think you need a custom filter for that if you don't want to rely on a certain style=xxx attribute on the tag:

$('*').filter(function() { /* check the background color of this */ });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.