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

DrANoel picture DrANoel · Aug 16, 2011 · Viewed 267.4k times · Source

Using only 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 tag elements.

<p data-foo="0"></p><br/><h6 data-foo="1"></h6>

Answer

Joe picture Joe · Aug 16, 2011

You can use querySelectorAll:

document.querySelectorAll('[data-foo]');