Aaron Aaron - 26 days ago 8
jQuery Question

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
?

Answer

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

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