1

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

1
  • you are giving all the parents the same ID. Try to make them different, eg by using `parent_${i}` Commented May 14, 2022 at 12:00

1 Answer 1

1

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I really didn't realize that I can only use id once, I was so focused on how to add a child to each

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.