Reputation: 6512
I have an html element that uses arrays inside the data attribute
<div data-area='["North America", "United Kingdom"]'>Test</div>
I have multiple data attributes pertaining to different "things"
<div data-area='["North America", "United Kingdom"]' data-job='["Programmer","Scientist"]'>test</div>
How can I go by searching through all the data attribute tags on the entire element based off of 1 value?
I'm trying to use a selector rather than looping through each data attribute, Is this possible?
Here is an example plus a fiddle of what I've attempted.
// search all data attributes of a div element that contains the given value and apply a hidden class
// this should search every data attribute for "Programmer"
$('[data-*="Programmer"]').addClass('hidden');
Upvotes: 2
Views: 176
Reputation: 254944
I can only think of this solution:
$('body *').addClass(function() {
var data = $(this).data();
for (var i in data) if (data.hasOwnProperty(i)) {
if (data[i].indexOf('Programmer') > -1) {
return;
}
}
return 'hidden';
});
It's not optimal since it iterates over all DOM nodes, but I don't see other way to select all the nodes that have data-*
attribute.
If there are some more precise criterias on what nodes should be checked - it's highly recommended to change a selector accordingly (instead of body *
)
Upvotes: 1