Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert the same html element twice?

Tags:

javascript

Here's a part of my code

  elementol = document.createElement("ol");
  var longueur = titres.length;
  for ( k = 0; k < longueur ; ++k) {
    elementli = document.createElement("li");
    elementli.appendChild(
      document.createTextNode(
        titres[k].firstChild.nodeValue
      )
    );
    elementol.appendChild(elementli);
  }
  body = document.getElementsByTagName("body").item(0);
  body.appendChild(elementol);

The problem is If I try to find another Item and append, nothing work. For example if I double the lines at the end to give something like :

  body = document.getElementsByTagName("body").item(0);
  body.appendChild(elementol);
  body = document.getElementsByTagName("body").item(0);
  body.appendChild(elementol);

Only the first append work, not the second , so I don't have my result twice. I'm new with this language, and found some code, but I don't know how to add multiple value.

thanks

like image 950
baronming Avatar asked Nov 25 '13 20:11

baronming


1 Answers

A node can't be in two locations in the tree at once.

Use .cloneNode(true) for the second one to clone it.

document.body.appendChild(elementol);
document.body.appendChild(elementol.cloneNode(true));

The true argument makes it clone its descendants as well.

like image 132
Blue Skies Avatar answered Oct 13 '22 23:10

Blue Skies