Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery - Attach (duplicate, clone) li and put it above a li

Is it possible to clone a specific < li> and put it above an other specific < li>?
Any clue would help me..?

HTML

<div id="main">
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
</ul>
</div>

Pseudo Javascript (JQuery)

$('#main ul li:eq(3)').duplicateAndPutAbove('#main ul li:eq(2)');

HTML Result

<div id="main">
<ul>
<li>Item 1</li>
<li>Item 3</li> <!-- Item 3 was duplicated (or cloned) and then putted ABOVE Item 2 -->
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
</ul>
</div>
like image 602
Tomkay Avatar asked Dec 13 '22 16:12

Tomkay


2 Answers

You were really close, you wanted clone and insertBefore (and remember that eq is zero-based):

$('#main ul li:eq(2)').clone().insertBefore('#main ul li:eq(1)');

Live example

like image 106
T.J. Crowder Avatar answered Dec 28 '22 10:12

T.J. Crowder


$('#main ul li:eq(3)').clone().insertBefore('#main ul li:eq(2)');

Demo: http://jsfiddle.net/karim79/8LpuN/

like image 27
karim79 Avatar answered Dec 28 '22 08:12

karim79