Home > Mobile >  JavaScript How to create elements into each created element?
JavaScript How to create elements into each created element?

Time:05-15

I'm trying to put a content div into each parent div, but this way it puts all the content divs to the first parent div, not each parent div. I've tried to do it in 2 for loops, tried forEach, but just can't figure it out.

        for (let i = 0; i < 5; i  ) {
           const parent = document.createElement("div");
           parent.classList.add("parent");
           parent.setAttribute("id","parent");
           document.getElementById("container").appendChild(parent);
           const content = document.createElement("div");
           content.classList.add("content");
           document.getElementById("parnet").appendChild(content);
        }

Ty for your answer

CodePudding user response:

You're using id's to select your parents with. But you can't have multiple elements with the same id value. getElementById will also look for the first occurence of the id, so you will always get the first parent element.

Besides that, you already have a reference to the parent in your parent variable. No need to look it up again, just use the reference you already have.

const container = document.getElementById("container");

for (let i = 0; i < 5; i  ) {
  const content = document.createElement("div");
  content.classList.add("content");

  const parent = document.createElement("div");
  parent.classList.add("parent");

  parent.append(content);
  container.append(parent);
}
  • Related