- Instant help with your JavaScript coding problems

Get element with data- attribute using vanilla JavaScript

Question:
How to get element with data- attribute using vanilla JavaScript?
Answer:
const elements = document.querySelectorAll("li[data-id='2']");
Description:

You can find elements in the DOM based on data-* attributes by using the querySelectorAll pure vanilla JavaScript method.

The code above select the second li elements from this code:

<ul>
<li data-id="1">1</li>
<li data-id="2">2</li>
<li data-id="3">3</li>
</ul>
Share "How to get element with data- attribute using vanilla JavaScript?"