I'm facing a challenge here. I need to generate 4 new elements with the same class but different IDs without repeating code. Unfortunately, my loop doesn't seem to be working as expected.
I've spent the last 2 hours trying to crack this puzzle (even did a lot of Google research), inspecting elements using console.log, and printing them within the loop. At one point, I had to resort to console.dir to check the attributes of the created [object HTMLDivElement].
The script I have looks like this:
columnsArray = ["first", "second", "third", "fourth"]
for (var i = 0; i < columnsArray.length; i++ ) {
let name = columnsArray[i]
name = document.createElement("div");
name.className = "container"
name.setAttribute("id", name.name)
document.querySelector("#board" + boardId).appendChild(name);
}
I'm wondering if there's a more straightforward way (worth attempting) to achieve my goal? Apart from the following workaround:
let first = document.createElement("div");
let second = document.createElement("div");
let third = document.createElement("div");
let fourth = document.createElement("div");
first.className = "container"
second.className = "container"
third.className = "container"
fourth.className = "container"
first.setAttribute = "first"
second.setAttribute = "second"
third.setAttribute = "third"
fourth.setAttribute = "fourth"
document.querySelector("#board" + boardId).appendChild(first);
document.querySelector("#board" + boardId).appendChild(second);
document.querySelector("#board" + boardId).appendChild(third);
document.querySelector("#board" + boardId).appendChild(fourth);
Appreciate any help in advance;)