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?
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';
})
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With