简体   繁体   中英

How can I change the order of list elements using Jquery?

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 .

Fiddle

your jquery would be . you can use insertBefore.

$('#list').find('li:eq(1)').insertBefore('li:eq(0)');

DEMO

Try,

var lists = $('#list li');
lists.filter(':contains(2)').insertBefore(lists.filter(':contains(1)'));

DEMO

or

var lists = $('#list li');
lists.filter(':nth-child(2)').insertBefore(lists.filter(':nth-child(1)'));

DEMO

To make the first one last regardless of number of items:

$("#list li:last").after($("#list li:first"));

Demo

   $("#list").prepend($("li:eq(1)"));

DEMO

or

 $("li:eq(1)").prependTo("#list");

DEMO

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>

Fiddle

演示尝试这个,

  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.

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