Shafizadeh
Shafizadeh

Reputation: 10380

how to select element based one style attribute in jquery?

I have a <h2> with this style:

<h2 style="color='#ccc'; font-size='12px'; margin='10px';"></h2>

How can I select that just with 1 property ? like this: $("h2[style=color='#ccc']");

I can do that with all property, like this:

$("h2[style='color=#ccc; font-size=12px; margin=10px;']");

But I want to select via just one property (color), is it possible ?

Upvotes: 2

Views: 63

Answers (1)

Alex Shesterov
Alex Shesterov

Reputation: 27595

You may use the attribute-contains-selector:

$("h2[style*='color=#ccc']")

Please note that color: '#ccc' is not a valid CSS; the color code must not be quoted.

Also note that this solution uses a single selector, but it does not handle non-inline CSS, nor the whitespace inside inline CSS.

If you want to handle CSS properly, you have to use filter() — see this answer for an example. Note that it may have some performance impact.

Also, please consider using classes for JS logic.

Upvotes: 2

Related Questions