Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select all elements with a "data-xxx" attribute without using jQuery

Using only pure JavaScript, what is the most efficient way to select all DOM elements that have a certain data- attribute (let's say data-foo).

The elements may be different, for example:

<p data-foo="0"></p><br/><h6 data-foo="1"></h6> 
like image 613
JLeonard Avatar asked Aug 16 '11 20:08

JLeonard


People also ask

How do you get all elements with a data attribute?

To get all DOM elements by a data attribute, use the querySelectorAll method, e.g. document. querySelectorAll('[data-id]') . The querySelectorAll method returns a NodeList containing the elements that match the specified selector.

How do you select all elements by tag?

The * selector selects all elements. The * selector can also select all elements inside another element (See "More Examples").

How do you get the value of data attribute in JS?

We can either use the dataset property to get access to the data attributes or use the . getAttribute() method to select them by specifically typing their names.

When working with attribute selectors how can you select elements which contain a particular attribute value?

The [attribute|="value"] selector is used to select elements with the specified attribute, whose value can be exactly the specified value, or the specified value followed by a hyphen (-). Note: The value has to be a whole word, either alone, like class="top", or followed by a hyphen( - ), like class="top-text".


2 Answers

You can use querySelectorAll:

document.querySelectorAll('[data-foo]'); 
like image 126
Joe Avatar answered Sep 27 '22 20:09

Joe


document.querySelectorAll("[data-foo]") 

will get you all elements with that attribute.

document.querySelectorAll("[data-foo='1']") 

will only get you ones with a value of 1.

like image 43
Joseph Marikle Avatar answered Sep 27 '22 20:09

Joseph Marikle