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

190
Views
Why does this js code only change the last div?

The button should replace all the letters (a, b, c) with 'test', but it only replaces the last (c).

If I replace the line of code inside of updateHTML() with the commented line, the code works as intended. Can someone explain what the difference is and why the lines of code work differently.

My js and html files:

let names = ["a", "b", "c"];
let objs = [];
let container;
let form;

class Class {
   constructor(name) {
      this.name = name;
      this.buildHTML();
   }

   buildHTML() {
      container.innerHTML += `
        <div id="${this.name}">
            ${this.name}
        </div>`
      this.inner_container = document.getElementById(this.name);
   }

   updateHTML() {
      this.inner_container.innerHTML = "test";
      // document.getElementById(this.name).innerHTML = "test";
   }
}

function main() {
   container = document.getElementById("container");

   for (var name in names) {
      objs.push(new Class(names[name]));
   }

   form = document.getElementById("form");
   form.addEventListener('submit', eventHandler_submit_form);
}

function eventHandler_submit_form(event) {
   event.preventDefault();
   for (var obj in objs) {
      objs[obj].updateHTML();
   }
}
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Sample Text</title>
</head>

<body onload="main()">
    <form id="form">
        <button type="submit">Submit</button>
    </form>

    <div id="container"></div>
</body>

</html>

about 4 years ago · Juan Pablo Isaza
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!