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

193
Visualizações
How to add event handlers to button elements rendered in an OL using Javascript and get the index position?

I'm trying to build a simple to do list application. I've linked my input field to an array which gets rendered out as an ordered list, and there are two buttons added to each item, one to state "completed" and one for "remove".

I've having difficulty with two parts: 1) adding event handlers to the buttons rendered out in the OL (I've managed to in the code below but I'm not sure if it's the right way. Part 2) identifying the index of the item so that I can modify it with the completed and remove buttons.

I've tried to use event delegation to tackle part 1 but I'm not sure if this is correct, and I don't know how to relate it to part 2.

document.getElementById("parent-list").addEventListener("click", function(e) {
    if(e.target && e.target.nodeName == "BUTTON") {
        console.log(e.target);
    }
});
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

One way would be to add the index as an attribute of the LI element within your ordered list. Then you could access it like so:

document.getElementById("parent-list").addEventListener("click", function(e) {
  if (e.target && e.target.nodeName == "BUTTON") {
    const list = e.target.closest('li[data-idx]');
    const idx = list.dataset.idx;
    console.log(e.target, list, idx);
  }
});
<ol id='parent-list'>
  <li data-idx='1'><button class='action'>click me</button></li>
  <li data-idx='2'><button class='action'>click me</button></li>
</ol>

Of course this is just a proof of concept, you'd need to add error handling and such.

about 4 years ago · Juan Pablo Isaza Relatório

0

First off, you should keep track of the items

const items = document.querySelectorAll('.my-classname');

This will create an items array where you can do all sorts of stuff, like .forEach(). This is great, because you need the index of the item as well.

That would solve part 2.


Now, for part 1..

You should add classnames to each buttons, like

<button class="completed-btn"></button>
<button class="remove-btn"></button>

The reason you need this is to be able to differentiate them and their handlers.

Next step is same as with items. You want to keep track of each button.

const completedButtons = document.querySelectorAll('.completed-btn');
const removeButtons = document.querySelectorAll('.remove-btn');

You can now add your handlers

completedButtons.forEach((button, i) => {
  button.addEventListener("click", function (e) { 
    const item = items[i];
    const target = e.target;

    // do stuff
  });
});

removeButtons.forEach((button, i) => {
  button.addEventListener("click", function (e) { 
    const item = items[i];
    const target = e.target;

    // do stuff
  });
});

The variable i will match the index of the clicked item's button, therefore will match the index of the item.

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