Dennis Martinez
Dennis Martinez

Reputation: 6512

Is there a way to search an array inside multiple data attributes of an html element based on a single value?

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');

http://jsfiddle.net/pWdSP/1/

Upvotes: 2

Views: 176

Answers (1)

zerkms
zerkms

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';
});

http://jsfiddle.net/pWdSP/4/

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

Related Questions