javascript – Select element based on data-id attribute


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

  <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>

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


In pure javascript it can be like this:


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

Scroll to Top