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>