I'm trying to increase my understanding of jQuery. Please consider the following code.
if ($('.myClass').data('id') == '123') {
}
How does this work? It looks simple enough until you understand that $()
returns a collection of elements. So what does the code above do exactly? How does it make sense to compare the value of the data-id attribute for a collection of elements like this?
(I understand I can use each()
to explicitly test each element in the collection. My question is about what the code above does.)
.data('id')
returns the value for the first item in the collection, but .data('id','xyz')
will set the value for all items in the collection - much the same behaviour as other jQuery methods like .html()
, .text()
, etc.
It may not seem to make sense to just test the first in an if
statement like that, but it makes more sense for cases where you know there will be exactly one element, for example when your selector is an id, or when you use $(this).data('id')
inside an event handler or something.
If you are asking how to test whether all items in the collection have a particular data value you can do this:
var $col = $('.myClass');
if ($col.length === $col.filter(function(){return $(this).data('id') === '123';}).length) {
// do something
}
Or if you just want to know if at least one has that data value:
if ($('.myClass').filter(function(){return $(this).data('id') === '123';}).length > 0) {
// do something
}
I believe if you're trying to get a value through a jquery function, it returns the value from the first item in the collection. for example if you have:
<div class='1'></div>
<div class='2'></div>
<div class='3'></div>
and you run:
$('div').attr('class');
it will return "1". I don't know if this is uniform through all jQuery functions, but this is the expected behavior.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With