Faraderegele
Faraderegele

Reputation: 187

A weird contains (*) jQuery selector

Hello I have this html structure.

<span class="radio" style="background-position: 0px 0px; "></span>

I just want to check the state when the style changes to

<span class="radio" style="background-position: 0px -50px; "></span>

so I guess this code will match:

var isChecked = $('.yleis span.radio[style*="-50"]')?true:false;

console.log(isChecked);

But why is this always return true?

Upvotes: 1

Views: 93

Answers (3)

Richard Dalton
Richard Dalton

Reputation: 35793

The result of a jQuery selector ($('div) etc) will always be a jQuery object. To turn this into a boolean of whether any results exist, check the length property. Anything other than 0 is true.

var isChecked = $('.yleis span.radio[style*="-50"]').length ? true : false;

You also don't need the : after radio.

http://jsfiddle.net/sfkkh/

Upvotes: 2

Guffa
Guffa

Reputation: 700562

The jQuery call always returns a jQuery object, even if the selector matches zero elements.

Check the length of the jQuery object to see if it matched anything:

var isChecked = $('.yleis span.radio[style*="-50"]').length > 0;

(As Plutor noted, the colon shouldn't be in the selector.)

Upvotes: 6

pimvdb
pimvdb

Reputation: 154898

You assume that an empty jQuery object (no elements matched) would yield you false and a non-empty one true. This is not true - a jQuery object is always "something". You want to check whether it's empty. Use $(...).length > 0 instead (which gives you a boolean - no ternary operator needed).

Upvotes: 2

Related Questions