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

353
Visualizações
How to get the index of an element in an array when it is clicked?

Here is the piece of HTML code. I captured the buttonElements using document.getElementsByClassName('buttonEl') and added a eventListener. And I want the index of the particular button when it is clicked.

<div class="action">
  <div class="buttonEl"></div>
  <div class="buttonEl"></div>
  <div class="buttonEl"></div>
</div>
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

This would be one way of doing it...

document.querySelectorAll will get an array of elements (buttons) based on the class selector.

We then loop over this array using forEach - button is the current element we are iterating over while index is the index of that element in the array.

Finally, while looping, we attach a "click" event listener to each button and when that event is fired, we console.log the index from earlier.

const buttons = document.querySelectorAll('.buttonEl')
buttons.forEach(function(button, index){
  button.addEventListener('click', function(){
    console.log(index)
  })
})
.action{
  display: flex;
  justify-content: space-around;
}

.buttonEl {
  background-color: #CCC;
  padding: 10px;
  border-radius: 5px;
}
<div class="action">
  <div class="buttonEl">Foo</div>
  <div class="buttonEl">Bar</div>
  <div class="buttonEl">Baz</div>
</div>

about 4 years ago · Juan Pablo Isaza Relatório

0

I believe you're looking for the indexOf array method.

// Arrays have the indexOf method, but NodeLists do not
const buttons = Array.from(document.querySelectorAll('.buttonEl'));
const buttonParent = document.querySelector('.action');
buttonParent.addEventListener('click', (evt) => {
  let target = evt.target;
  let index = buttons.indexOf(target);
  console.log(index);
});
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