danyolgiax
danyolgiax

Reputation: 13086

Selector for multiple attributes values in AND condition

I've the following html:

<div id="wrapper">
    <div>a</div>
    <div tag="one, two, three">b</div>
    <div tag="three">c</div>
    <div tag="four, one">d</div>
    <p>e</p>
</div>

with JQuery I need to .hide all #wrapper children not contains a well known array of tag in AND condition.

Example:

For one, three I have:

<div id="wrapper">
    <div tag="one, two, three">b</div>
</div>

For a single tag I managed it to work in this way:

var tag= tagArray[0];

$("#wrapper> *:not([tag='" + tag + "'])").each(function (index, value) {
      $(value).hide();
}); 

But how to work with the full array? Is this the right way to accomplish this?

Upvotes: 1

Views: 200

Answers (1)

Karl-Andr&#233; Gagnon
Karl-Andr&#233; Gagnon

Reputation: 33870

You can use this code :

var tagArray = ['three', 'two']


$.each(tagArray, function(){
    var tag = this;
    $("#wrapper> *").filter(function(){
        var regexp = new RegExp('\\b'+tag+'\\b');
        return !($(this).attr('tag') && $(this).attr('tag').match(regexp));
    }).hide()
})

You loop over the array of tag and then compare them with a regexp.

Also, it would be better to use HTML5 data-* attribute instead of customs ones.

Fiddle

Upvotes: 1

Related Questions