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

182
Visualizações
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 à 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