Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Working with jQuery Collections

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.)

like image 831
Jonathan Wood Avatar asked Oct 21 '22 22:10

Jonathan Wood


2 Answers

.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
}
like image 156
nnnnnn Avatar answered Oct 24 '22 18:10

nnnnnn


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.

like image 24
kennypu Avatar answered Oct 24 '22 16:10

kennypu