Select elements that contain a particular "date" attribute

9

On the page there are several elements with data attributes. To avoid going to add CSS classes to the elements, making the page code denser, I would 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 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?

    
asked by anonymous 14.01.2014 / 15:33

3 answers

8

You can use the following:

div[data-my-target]

This looks for elements that contain this attribute. You can also filter the attribute by value. For example:

div[data-my-target="John"]

The = home elements whose attribute is the last string. 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 the performance of using a class is better (I have not tested).

Useful reference : MDN CSS Attribute selectors

    
14.01.2014 / 15:37
5

The answer from bfavareto is correct.

Just to document 2 more examples and differences from performance .

1:

$('div[data-my-target]');  // mais compatível com browsers antigos

2:

$('div').filter('[data-my-target]'); 
// ou:
arrayEmCache.filter('[data-my-target]'); // no caso de já haver uma array de elementos em cache

3:

document.querySelectorAll('[data-my-target]'); // mais rápida mas não compatível com IE<8
    
14.01.2014 / 16:31
0

Most current template:

var target = $("#suaDIV").data("my-target");
    
07.06.2017 / 16:15