Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

181
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda