• 1
  • 2
  • 3How to reorder list i...">

    How to reorder list items using jQuery?

    I have ul li as below:

    <ul id="list">
        <li>1</li>
        <li>2</li>
        <li>3</li>
    </ul>
    

    How to reorder list items using jQuery? So when loading the new list should look like this:

    <ul id="list">
            <li>2</li>
            <li>1</li>
            <li>3</li>
    </ul>
    

    Can i use jQuery?

    +4
    source share
    7 answers

    Search like this,

    $("#list li:eq(0)").before($("#list li:eq(1)"));
    
    Selector

    eqselects an item with an index. Then you can use before()or after()to change the position.

    Fiddle

    +5
    source

    your jquery will be. you can use insertBefore.

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

    Demo

    +4
    source

    ,

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

    DEMO

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

    DEMO

    +2

    , :

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

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

    DEMO

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

    DEMO

    +1

    ,

      alert($('li').eq(0).insertAfter($('li').eq(1)));
    
    +1

    html :

    <ul id="list">
        <li>1</li>
        <li>2</li>
        <li>3</li>
    </ul>
    

    you can use after/ beforeor appendTo/ prependToto manage lists and other nodes DOM:

    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 that you will have a list like this:

    <ul id="list">
        <li>2</li>
        <li>1</li>
        <li>3</li>
    </ul>
    

    Fiddle

    0
    source

    Source: https://habr.com/ru/post/1546645/


    All Articles