jQuery if any item in collection has data-id equal foo

1.5k views Asked by At

Imagine I have a collection of .item divs. Each with it's own data-item-id attribute. I want to check if any of the .data .items has a data-item-id equal to x.

Because if any of the items have that id, I will not be adding that .item again to the .data listing div.

How can I do this using jQuery?

if ($('.data .items').data('itemId')) { ????
}
2

There are 2 answers

0
zigdawgydawg On

This should return items where data-item-id is equal to x:

var items = $('.data .items[data-item-id="x"]');

or like this:

var items = $('.data .items').filter(function() { return $(this).data('item-id') == 'x'; });

And in an if:

if (items.length) {
    // do something
}
0
sudhansu63 On

You can try the following code.

 $('.data .items[data-item-id=foo]').DoSomething(function(){ 
    //Do something. 
 });  
 //This filters the elements having this attribute and value as x.