Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

101
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!