Question:
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.
Example
<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.
Question
How can I select elements by the name of the data
attribute?
Answer:
You can use the following:
div[data-my-target]
This looks for elements that contain that attribute. It is also possible to filter the attribute by value. For example:
div[data-my-target="John"]
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 *=
:
div[data-my-target*="John"]
However, I believe that the performance of using a class is better (not tested).
Useful reference : MDN CSS Attribute selectors