Append child elements in parent

<div id = "a"></div>
<div id = "b"></div>
<div id = "ab"><div>

function addKids() 
{
    img1 = document.createElement("img");
    img1.src = // SOURCE1;
    document.getElementById("a").appendChild(a);

    img2 = document.createElement("img");
    img2.src = // SOURCE2;
    document.getElementById("b").appendChild(b);

    document.getElementById("ab").appendChild(a);
    document.getElementById("ab").appendChild(b);
}

This is what I want, Basically I want img1 in div A, img 2 in div B, and then both images in div AB. If I remove the code to appendChildren to AB, the images show up in their respective divs, but once the appendChildren is there, they only appear in AB. How can I make the images appear in each div correctly without too much extra coding?

Also, more images will constantly be added to div A and B. How can I get the last image of both divs into div AB?

Thanks!

Upvotes: 2

Views: 3522

Answers (1)

Ele
Ele

Reputation: 33726

The DOM elements can't be shared by different parents, cause that the last parent AB will be the only one for image a and b

An alternative is cloning these images using the function cloneNode()

function addKids() {
  a = document.createElement("img");
  a.src = 'https://i.sstatic.net/G2FO1.jpg?s=48&g=1';
    document.getElementById("a").appendChild(a);

  b = document.createElement("img");
  b.src = 'https://lh3.googleusercontent.com/-w_IWeYU4ynw/AAAAAAAAAAI/AAAAAAAAAF0/Xbzx7yhjooQ/photo.jpg?sz=48';
    document.getElementById("b").appendChild(b);

  var ab = document.getElementById("ab");
  ab.appendChild(a.cloneNode());
  ab.appendChild(b.cloneNode());
}

addKids();
<div id="a">a</div>
<div id="b">b</div>
<div id="ab">ab
  <div>

Upvotes: 3

Related Questions