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
?
The attr() method in jQuery is used to set or return the attributes and values of the selected elements. To set multiple attributes and values: $(selector). attr({attribute:value, attribute:value, ...})
In jQuery, you can select multiple elements by separate it with a comma “,” symbol.
A data attribute is a custom attribute that stores information. Data attributes always start with “data-” then followed with a descriptive name of the data that is being stored. You can have multiple data attributes on an element and be used on any HTML element.
Do the same as you already did... the attribute selectors can be chained:
$('.my-class[data-id="' + dataId + '"][data-id-index="'+dataIdIndex+'"]').append(myText);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With