Reputation: 187
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
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.
Upvotes: 2
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
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