Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

220
Visualizações
Can I use event.target to determine an index of <li> element?

Suppose i have a <ul></ul> with some number of <li></li> elements. And I wonder, what is the best way to get an index of the <li> element by clicking on its child (I have buttons inside)? Under the best way, I mean the most beginner-friendly, using vanilla JS. Maybe you, guys, have a couple of ideas to share?

I need that index to remove the related element from an array later on. What I've managed to write so far seems overcomplicated, since I have to assign ids to each element I want to click on.

function removeItem(e) {
   if (e.target.classList.contains('removeBtn')) {
      controller.tasks.splice(e.target.id, 1);
      view.renderInput(controller.tasks);
   } 
}
ulEl.addEventListener('click', removeItem);
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Suppose i have a <ul></ul> with some number of <li></li> elements. And I wonder, what is the best way to get an index of the <li> element by clicking on its child (I have buttons inside)?

Just use forEach which will give you the index as well like this:

const list = document.querySelectorAll('#someList li');
const btns = document.querySelectorAll('#someList button');

btns.forEach((btn, index) => {
    btn.addEventListener('click', () => {
    console.log(index);
    console.log(list[index]);
  });
});
<ul id="someList">
  <li>A <button>Click Me</button></li>
  <li>B <button>Click Me</button></li>
  <li>C <button>Click Me</button></li>
  <li>D <button>Click Me</button></li>
</ul>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda