JavaScript: Getting an element by data attribute

From The Travis van der Font Wiki
Jump to: navigation, search
jQueryL
$('p[data-test-slug="123"]');

Native JavaScript Example

Get NodeList of elements

var elem = document.querySelectorAll('[data-id="container"]')

html: <div data-id="container"></div>

Get the first element

var firstElem = document.querySelectorAll('[id="container"]')[0]

html: <div id="container"></div>

Target collection of nodes then select

document.getElementById('footer').querySelectorAll('[data-id="12"]')

html:

<div class="footer">
    <div data-id="12"></div>
</div>

Get multiple IDs

document.querySelectorAll('[data-section="12"],[data-selection="20"]')

html:

<div data-selection="20"></div>
<div data-section="12"></div>

Get items where the value starts with

document.querySelectorAll('[href^="https://"]')