Select element based on data-id attribute

3

How do I get the id in JavaScript which, 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 HTML above, I'd like to get the e2 id, since this is what has data-id="2" .

    
asked by anonymous 03.07.2018 / 18:12

2 answers

4

In pure javascript it can be like this:

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

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

document.querySelectorAll("[data-id='2']")[0].id
    
03.07.2018 / 18:14
4

You can use document.QuerySelector with the data-id='2' .

This function will return an element that matches the selector, if there is no element that meets the condition, it will return null .

var elemento = document.querySelector("[data-id='2']");
console.log('id: ${elemento.id} \ndata-id: ${elemento.dataset.id}');
<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>
    
03.07.2018 / 18:15