Append DOM Element twice with JavaScript

A DOM element can have only one direct parent. So if you want to add the same element to multiple containers you need to clone it. This can be done with JavaScript using cloneNode(deep). The variable deep is a boolean value which tells whether to include child elements or not.

Sample:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>Append DOM Element twice with JavaScript</title>
    <style type="text/css">
      * { margin: 0; padding: 0; border: 0; }
    </style>
  </head>
  <body>  
    <div id="container1"></div>
    <div id="container2"></div>
    <script type="text/javascript">
      var text = document.createElement('p');
      text.innerHTML = 'Hello World!';
      document.getElementById('container1').appendChild(text);
      document.getElementById('container2').appendChild(text.cloneNode(true));
    </script>
  </body>
</html>