Select element based on the data-id attribute

Asked

Viewed 375 times

3

Eat I make to catch 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 HTML above, I would like to receive the id e2, since this is the one that has data-id="2".

  • Why the negative? Everyone should be born knowing how to do it?

  • Thecoder, could confirm if you need to search for the element you have data-id=2 or what you want is the value 2?

  • I want to search if any element has data-id=2

  • Could pick up hair id direct, no?

  • The id is just for example. I am creating an API in which the other programmer can create his own button, just put this attribute to work

2 answers

5


In pure javascript can be like this:

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

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

document.querySelectorAll("[data-id='2']")[0].id
  • Thanks for the help, I use pure js!

4

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

This function will return an element that meets the selector, if there is no element that meets the condition will be returned 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>

  • Thanks for the help!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.