JavaScript: Getting an element by data attribute

From The Travis van der Font Wiki
Revision as of 17:31, 10 January 2018 by Travisfont (talk | contribs) (Created page with "jQueryL<syntaxhighlight lang="javascript"> $('p[data-test-slug="123"]'); </syntaxhighlight> '''Native JavaScript Example''' '''Get NodeList of elements''' <code>var elem =...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
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://"]')