Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter items based on data attribute in jQuery

Tags:

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?

like image 559
hilda_sonica_vish Avatar asked Dec 20 '25 23:12

hilda_sonica_vish


2 Answers

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';
})
like image 70
Pranav C Balan Avatar answered Dec 22 '25 14:12

Pranav C Balan


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>
like image 35
Hassan Imam Avatar answered Dec 22 '25 15:12

Hassan Imam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!