I have a ul li as below:
<ul id="list">
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
How can I change the order of list elements using Jquery? So that on load, the new list should look like:
<ul id="list">
<li>2</li>
<li>1</li>
<li>3</li>
</ul>
Is it possible to achieve using Jquery?
USe like this,
$("#list li:eq(0)").before($("#list li:eq(1)"));
eq
selector selects the element with index. Then you can use before()
or after()
to change the postion .
your jquery would be . you can use insertBefore.
$('#list').find('li:eq(1)').insertBefore('li:eq(0)');
To make the first one last regardless of number of items:
$("#list li:last").after($("#list li:first"));
If you use html like this:
<ul id="list">
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
you can use after
/ before
or appendTo
/ prependTo
to manipulate lists and other DOM
nodes:
var $list = $('#list'),
$items = $list.children(),
$firstItem = $items.first();
//remove first item from DOM
$firstItem.detach();
//set first item after second
$items.eq(1).after($firstItem);
And after this you will have such list:
<ul id="list">
<li>2</li>
<li>1</li>
<li>3</li>
</ul>
演示尝试这个,
alert($('li').eq(0).insertAfter($('li').eq(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.