hilda_sonica_vish
hilda_sonica_vish

Reputation: 757

Filter items based on data attribute in jQuery

I have a list of jQuery items found using

var groupedItems = $('div[data-group-id="'+groupId+'"]');

Each grouped item has a propery called

data-info={"isAvailable":"true","isValid":"false"}

from the groupedItem I want to filterOut only which has property isAvailable=true.

How can I filter based on data attribute?

Upvotes: 3

Views: 76

Answers (2)

Hassan Imam
Hassan Imam

Reputation: 22524

You can use filter to filter groupedItems which have isAvailable set to true inside info data attribute. Access data attribute using data().

var groupId = 1;
var groupedItems = $('div[data-group-id="'+groupId+'"]');
var info = groupedItems.filter(function(){ 
  return $(this).data('info').isAvailable == 'true';
});
console.log(info);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-group-id=1 data-info={"isAvailable":"true","isValid":"false"}>foo</div>

Upvotes: 1

Pranav C Balan
Pranav C Balan

Reputation: 115212

You can use jQuery filter() method to filter jQuery collection and where you can use data() method to get the property.

var groupedItems = $('div[data-group-id="' + groupId + '"]');

var res = groupedItems.filter(function() {
  // since property value starts with {, the data method
  // would parse if it's a valid JSON. So simply get the
  // property from the object and compare
  return $(this).data('info').isAvailable == 'true';
})

Upvotes: 1

Related Questions