Aaron
Aaron

Reputation: 3245

Using jQuery, how can I select elements by multiple data-attributes?

Consider this array of p tags indexed by data attributes.

<p class='my-class' data-id='0' data-id-index='1'></p>
<p class='my-class' data-id='0' data-id-index='2'></p>
<p class='my-class' data-id='1' data-id-index='1'></p>
<p class='my-class' data-id='1' data-id-index='2'></p>

To select a p by data-id and append text I can use:

$('.my-class[data-id="' + dataId + '"]').append(myText);

The above will append myText to all p tags with the same data-id. But what about if I wanted to select by both data-id and data-id-index?

Upvotes: 57

Views: 46962

Answers (2)

MDEV
MDEV

Reputation: 10838

You can do the same as you've already done, the attribute selectors can be chained:

$('.my-class[data-id="' + dataId + '"][data-id-index="'+dataIdIndex+'"]').append(myText);

Upvotes: 121

Codingwiz
Codingwiz

Reputation: 313

TLDR: When looking to return multiple elements with different data attribute and different data attribute value were both ARE NOT always present

<p class='my-class' data-attribute1='1'></p>
<p class='my-class' data-attribute2='2'></p>

// data-attribute1 OR data-attribute2
$(".my-class").filter(`[data-attribute1="${firstID}"],[data-attribute2="${secondID}"]`);

When looking to return multiple elements with different data attribute and different data attribute value were both ARE always present

<p class='my-class' data-attribute1='1' data-attribute2='1'></p>
<p class='my-class' data-attribute1='1' data-attribute2='2'></p>

// data-attribute1 AND data-attribute2
$(".my-class").filter(`[data-attribute1="${firstID}"][data-attribute2="${secondID}"]`);

@MDEV's answer is great but only works when both data attribute1 and data attribute2 are present in all elements. For progammers who need to find elements by different data attribute value when both are not always present, you can do as follow

$(`.my-class[data-attribute1="${firstID}"],[data-attribute2="${secondID}"]`);

This will return all elements who have firstID for data-attribute1 OR secondID as data-attribute2. The placement of the comma between the data attribute is crucial.

You can also use a filter like so

$(".my-class").filter(`[data-attribute1="${firstID}"],[data-attribute2="${secondID}"]`);

It also works for elements who have the same data attribute but with different attribute value

$(".my-class").filter(`[data-attribute1="${firstID}"],[data-attribute1="${secondID}"]`);

I was inspired by this post of @omarjebari on stackoverflow.

Upvotes: 0

Related Questions