Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

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?

like image 919
Aaron Avatar asked Aug 20 '13 08:08

Aaron


People also ask

How set multiple attributes in jQuery?

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, ...})

Can you select multiple elements in jQuery?

In jQuery, you can select multiple elements by separate it with a comma “,” symbol.

Can you have multiple data attributes?

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.


1 Answers

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

$('.my-class[data-id="' + dataId + '"][data-id-index="'+dataIdIndex+'"]').append(myText); 
like image 58
MDEV Avatar answered Oct 08 '22 02:10

MDEV