Select elements containing a particular "date" attribute

Asked

Viewed 14,251 times

9

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

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 containing an attribute data-my-target.

Question

How can I select elements by attribute name data?

3 answers

9


You can use the following:

div[data-my-target]

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

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

The = box 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 (I have not tested).

Useful reference (in English): MDN CSS Attribute selectors

5

The response of bfavareto is the right one.

Just to document 2 more examples and differences of 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

0

Most current model:

var target = $("#suaDIV").data("my-target");
  • how can I select the value of the attribute ?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.