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

100
Visualizações
Different onclicks for different elements when adding new elements using Javascript

I am working on a project where the user decides how many buttons are there, and then each button triggers a different function.

What I have done is: I have an input that asks "Enter the number of buttons" and a "Submit" button. When the "Submit" button is clicked, the value of variable n is set to the user-defined value.

I then have the following code (assuming the user has set n to 10):

for (i = 0; i < 10; i++) {
        var x = document.createElement('div');
        x.id = i;
        x.innerHTML = i;
        x.onclick = function() {alert(i)};
        document.body.appendChild(x);
   }

What I want is, that when div with id i is clicked, the pop-up message says i. But what has ended up happening is, that no matter which div I click, the pop-up message always says 10.

Why is this happening? How to fix this?

about 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

The only thing you need to change is the assignment of i inside the for-loop. Use let to define a locally-scoped variable. Also, use textContent instead of innerHTML for simple text. It is recommended to used const/let rather than var.

for (let i = 0; i < 10; i++) {
  const x = document.createElement('div');
  x.id = i;
  x.textContent = i;
  x.onclick = function() { alert(i) };
  document.body.appendChild(x);
}

about 4 years ago · Santiago Trujillo Relatório

0

You can use getAttribute to read the id of the elements. I show you an example:

for (i = 0; i < 10; i++) {
        var x = document.createElement('div');
        x.id = i;
        x.innerHTML = i;
        x.onclick = function(e) {
        let dataId= e.currentTarget.getAttribute("id")
        alert(dataId)
        };
        document.body.appendChild(x);
   }

Explanation:

getAtrribute() returns the value of an html attribute as a string, just enter the name of the attribute in braces to get the value. In this case I entered "id" which is the value we want to retrieve.

Also to get the value of the element where you click I use currentTarget, to accurately retrieve the value of the div that the iteration creates. If you use target, and inside the div you have more elements, this code will generate an error. Therefore, it is important to use currentTarget for this application.

about 4 years ago · Santiago Trujillo Relatório

0

By iterating over your NodeList elements, you can take this next approach. First of all, append all your created divs in your HTML and continue by looping through the elements list by document.querySelectorAll("div")

That way you select all elements and then assign an addEventListener to each one of the items. On your alert function, print this.id and it will return you the number of the id of the element which corresponds to your i index.

It would be the same also if you just put the whole addEventListener function inside the other loop.

I just separated both so you can understand it better.

for (i = 0; i < 10; i++) {
        var x = document.createElement('div');
        x.id = i;
        x.innerHTML = i;         
        document.body.appendChild(x);
   }
   
   
   let divs = document.querySelectorAll("div");
   
   for(var a= 0; a < divs.length; a++){
     divs[a].addEventListener("click", function(){
        alert(this.id);
     });
   
   }

about 4 years ago · Santiago Trujillo 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