简体   繁体   中英

Move first DOM after last DOM element in JavaScript

I am trying to move the FIRST item in a list AFTER the last item:

<ul>
    <li>1 (this DOM element needs to be moved after 1)</li>
    <li>2</li>
    <li>3</li>
</ul>

In jQuery this is easy:

$('#scrollable li:last').after($('#scrollable li:first')); 

But due to file restrictions I cannot use jQuery or an external lib. I have to use JavaScript. Does anyone have any ideas, on how I achieve this with vanilla JavaScript only? Any help would be very much appreciated.

UPDATE: thanks to @Mano for his answer.

You can use vanilla JavaScript like this: explained in comments

 var listitems = document.getElementsByTagName('li'); /* Get all list items */ var lastitem = listitems[listitems.length - 1]; /* Find the last list item */ var parentul = lastitem.parentNode; /* Find the parent element of the items */ parentul.insertBefore(lastitem, listitems[0].nextSibling); /* Replacement for insertAfter() */ 
 <ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5 (this DOM element needs to be moved after 1)</li> </ul> 

<ul id="list">
    <li>1</li>
    <li>2</li>
    <li>3 (this DOM element needs to be moved after 1)</li>
</ul>


var ul = document.querySelector("#list");

var children = ul.children;

var len = children.length;

ul.insertBefore(children[len-1],children[1]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM