Relocate elements in the DOM

2

How do I remove an element from its position and reallocate it in the DOM?

For example: in a <ul> , bring the last <li> to the top / first position.

I saw this in jQuery, with the function appendTo() , and would like to know how to do the same with pure javascript.

    
asked by anonymous 22.04.2017 / 02:45

1 answer

2

You can use .insertBefore() syntax is:

elementoPai.insertBefore(novoElemento, elmentoReferência);

Example:

var ul = document.querySelector('ul');
var primeiro = document.querySelector('ul li:first-of-type');
var ultimo = document.querySelector('ul li:last-of-type');
ul.insertBefore(ultimo, primeiro);
<ul>
  <li>Primeiro ?</li>
  <li>Meio</li>
  <li>Ultimo ?</li>
</ul>

or more compactly:

var ultimo = document.querySelector('ul li:last-of-type');
ultimo.parentNode.insertBefore(ultimo, ultimo.parentNode.firstChild);
    
22.04.2017 / 09:54