jquery – Select elements that contain a particular "date" attribute


On the page there are several elements with data attributes. To avoid going around adding CSS classes to elements by making the page code denser, I'd like to select elements by the name of the data attribute.


<div id="myDiv" class="text banana" data-my-target="John"></div>
<div id="myOther" class="text bread" data-my-target="Doe"></div>
<div id="myBother" class="text fun" data-my-girl="Jane"></div>

The idea is to apply a certain action via jQuery to elements that contain a data-my-target attribute.


How can I select elements by the name of the data attribute?


You can use the following:


This looks for elements that contain that attribute. It is also possible to filter the attribute by value. For example:


O = matches elements whose attribute is the string passed. If you want to partially match the value "John" (for example, if the value is "John Paul"), use *= :


However, I believe that the performance of using a class is better (not tested).

Useful reference : MDN CSS Attribute selectors

Scroll to Top