Jousi
Jousi

Reputation: 476

Trying to append child to all elements with same class name

I am trying to use the appendChild() method to add a document.createElement("div") element to multiple <div> elements with the same class name.

I have tried this way:

const childElement = document.createElement("div");
childElement.className = "second";
const parentObject = document.getElementsByClassName("first");

[...parentObject].map(parent => parent.appendChild(childElement))

Which didnt work, so I tried:

for(let i = 0; i < parentObject.length; i++){
  parentObject[i].appendChild(childElement);
}

The only way it worked was if I wrote the html element myself and then added it to the innerHTML of each parent:

[...parentObject].map(parent => parent.innerHTML = "<div class='second'></div>")

But since I am generating all different kind of HTML element tags, like IMG, DIV, SPAN I need the convenience of calling the createElement() method.

Has anyone any experience with this?

Upvotes: 1

Views: 2549

Answers (1)

Jordan Running
Jordan Running

Reputation: 106027

An element can only exist in one place in the DOM. What you need to do is create a new element to append to each parent:

const parentObject = document.getElementsByClassName('first');

[...parentObject].forEach((parent, i) => {
  const childElement = document.createElement('div');
  childElement.className = 'second';
  childElement.innerHTML = `second ${i}`;
  parent.appendChild(childElement)
});
div { padding: 5px; }
.first { background-color: pink; display: inline-block; }
.second { background-color: lightblue; }
<div class="first">first</div>
<div class="first">first</div>
<div class="first">first</div>
<div class="first">first</div>

Upvotes: 6

Related Questions