Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 896
Leo T Abraham Avatar asked Jul 01 '14 05:07

Leo T Abraham


2 Answers

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

like image 130
Anoop Joshi P Avatar answered Sep 17 '22 12:09

Anoop Joshi P


your jquery would be . you can use insertBefore.

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

DEMO

like image 22
Amit Kumar Avatar answered Sep 16 '22 12:09

Amit Kumar