javascript – Select element based on data-id attribute

Question:

How do I get the id in JavaScript that, in HTML, is data-id="2" ?

<ul>
  <li data-id="1" id="e1">Elemento 1</li>
  <li data-id="2" id="e2">Elemento 2</li>
  <li data-id="3" id="e3">Elemento 3</li>
</ul>

For example, for the above HTML I would like to get the id e2 , as this is the one with data-id="2" .

Answer:

In pure javascript it can be like this:

document.querySelectorAll("[data-id='2']")

As it will return an array of elements, you need to check if it returned any, and get the first element, then the id:

document.querySelectorAll("[data-id='2']")[0].id
Scroll to Top