nickf
nickf

Reputation: 546035

How do you select elements based on their style?

Using jQuery, how would you find elements which have a particular style (eg: float: left), regardless of whether it's an inline style or one defined in a CSS file?

Upvotes: 27

Views: 14694

Answers (3)

Eran Galperin
Eran Galperin

Reputation: 86805

Using the filter function:

$('*').filter(function() {
     return $(this).css('float') == 'left';
});

Replace '*' with the appropriate selectors for your case.

Upvotes: 42

Kenan Banks
Kenan Banks

Reputation: 211982

This is gonna be slow. Like REALLY slow. If you know you need to select all elements with a given CSS style, you will see much better performance by applying a single additional css rule to each element, and then selecting by that rule.

It's going to be MUCH faster and more readable to boot.

CSS:

.float-left {float:left}

Javascript:

$('.float-left');

Upvotes: 11

Genericrich
Genericrich

Reputation: 4641

Well, I don't know if I would approach this this way. Why not just rename those elements with a consistent ID or class name, and select that?

If that's not an option, this should work:

this.getElementsByTagName('div').item(0).style.float = 'left';

I think.

Upvotes: -2

Related Questions