Search code examples
javascriptdomappendchild

How to insert the same element on beginning and on the end of the list with insertBefore and appendChild?


I would like to add elements with the same text on the end and at the beginning of the list. I want use appendChild and insertBefore. But, if I do this in following way is added only one element, this which is as last in the code of the script:

var list = document.getElementsByTagName('ul')[0];
var firstElement = list.firstChild;
var newElement = document.createElement('li');
var newText = document.createTextNode('new text');
newElement.appendChild(newText);

list.appendChild(newElement);
list.insertBefore(newElement, firstElement);
<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
</ul>


Solution

  • You have to clone the element you want to insert. In your code you are "moving" the element from the button to the top, because you dealing with the same item which can only exist once in the html.

    So just add a .cloneNode(true) and a cloned item can be at the top and at the other one at the bottom.

    var list = document.getElementsByTagName('ul')[0];
    var firstElement = list.firstChild;
    var newElement = document.createElement('li');
    var newText = document.createTextNode('new text');
    newElement.appendChild(newText);
    
    list.appendChild(newElement);
    list.insertBefore(newElement.cloneNode(true), firstElement);
    <ul>
      <li>1</li>
      <li>2</li>
      <li>3</li>
    </ul>