Using jQuery, how can I select elements by multiple data-attributes?
JqueryJquery 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);