Reallocate elements in the DOM

Asked

Viewed 83 times

2

How do I remove an element from your position and relocate it in the DOM?

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

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

1 answer

2


You can use the .insertBefore() the 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 in a more compact way:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.