How to move lists

2020-05-10 08:02发布

I have something like this:

<ul>
<li id="li1">1</li>
<li id="li2">2</li>
<li id="li3">3</li>
</ul>

And I wonder if there is possible to move the list number 3, to the place of the list number 1 using javascript or jquery, like this:

<ul>
<li id="li3">3</li>
<li id="li2">2</li>
<li id="li1">1</li>
</ul>

Thanks for you time!

3条回答
狗以群分
2楼-- · 2020-05-10 08:21

No jQuery solution :

var list = document.getElementsByTagName('ul')[0],
    items = list.getElementsByTagName('li'),
    i = items.length;
while (i--) list.appendChild(items[i]);

Here is a demo : http://jsfiddle.net/wared/tJaJ9/.


Based on cookie monster's suggestion :

var list = document.getElementsByTagName('ul')[0],
    i = list.children.length;
while (i--) list.appendChild(list.children[i]);

Just for fun :

var list = document.getElementsByTagName('ul')[0],
    items = Array.prototype.slice.call(list.children);
while (items.length) list.appendChild(items.pop());

A jQuery one :

$('ul').append($('li').get().reverse());
查看更多
不美不萌又怎样
3楼-- · 2020-05-10 08:24

You can use ajax sortable jquery plugin. One of my recommendation tutorial is Sortable Lists Using jQuery UI . Here user can re-order list using cursor pointer.

查看更多
做个烂人
4楼-- · 2020-05-10 08:26

This should do the trick for you.

var length = $('ul li').length;

while (length--) $('ul').append($('ul li')[length]);

Here is a working jsfiddle

查看更多
登录 后发表回答