3

I know how to select elements by attribute like this:

<input value="myvalue" />
$('input[value="myvalue"]')

But how it is possible to select dom elements with specified css rules set. For example i need to select all elements with css "background-position" set;

1
  • use :input instead of input because :input select all kind of input element like input,button,submit,radio,checkbox etc. Commented Oct 20, 2011 at 12:48

1 Answer 1

4

There doesn't appear to be a jQuery selector for this, but you could use a .filter() to reduce a selector to suit your needs:

$('div').filter(function() {
    return ($(this).css('backgroundPosition')); // tests for existence
});

However, the problem here is that even if 'background-position' isn't set, some browsers set it to default values. You'll have to compare against those default values, but you won't be able to tell if those values were explicitly set in a stylesheet or not.

(Update: IE8 returns $(this).css('backgroundPosition') as "undefined" no matter what. The workaround is to test for 'backgroundPositionX' and/or 'backgroundPositionY' individually. However, while the defaults should be "0%", IE8 reports a default of "0px" instead. Test for both.)

(Update 2: Firefox doesn't return individual properties, only combined 'background-position'; IE8 doesn't return combined, only individual. Webkit will do both.)

$('div').filter(function() {
   return ($(this).css('backgroundPosition') !== "0% 0%" // firefox, webkit
        && $(this).css('backgroundPositionX') !== "0px"  // ie8
        && $(this).css('backgroundPositionY') !== "0px");
});

http://jsfiddle.net/mblase75/s8dx2/23/

Sign up to request clarification or add additional context in comments.

4 Comments

I have a feeling this will give false positives in some browsers.
In Chrome at least this will return all div elements whether you've set background-position or not (background-position is 0% 0% unless you've set it as something else): jsfiddle.net/LGmEp
Yes, it seems to be heavily browser-dependent -- and not all CSS attributes have default values.
This is why cross-browser testing is so important, even with jQuery leveling the field. Interested parties should look at the bug report at bugs.jquery.com/ticket/4295 , but the upshot is that different browsers report grouped CSS properties like margin and border very differently, and jQuery will not (at present) re-combine them.

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.