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

Jquery

Jquery Problem Overview


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?

Jquery Solutions


Solution 1 - Jquery

Do the same as you already did... the attribute selectors can be chained:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAaronView Question on Stackoverflow
Solution 1 - JqueryMDEVView Answer on Stackoverflow