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
ifstatement 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:
Or if you just want to know if at least one has that data value: