JQuery - How to move a li to another position in the ul? (exchange 2 li's)
Asked Answered
A

2

8

What is a cool way to apply this? I need a script that exchange two < li>'s position in an < ul>. It think that should be possible to achieve. Thanks for your response.

HTML

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

Pseudo Javascript (JQuery)

$("#awesome ul li:eq(1)").exchangePostionWith("#awesome ul li:eq(3)");

HTML Result

<div id="awesome">
<ul>
<li>Item 1</li>
<li>Item 4</li>
<li>Item 3</li>
<li>Item 2</li>
<li>Item 5</li>
</ul>
</div>
Alpheus answered 6/1, 2011 at 8:7 Comment(0)
P
29

You can use jQuery's .after() for moving elements around. I cloned one of them so the original can remain as a placeholder. It's like if you wanted to switch variables a and b, you'd need a third temporary variable.

$.fn.exchangePositionWith = function(selector) {
    var other = $(selector);
    this.after(other.clone());
    other.after(this).remove();
};

Now your pseudocode $("#awesome ul li:eq(1)").exchangePositionWith("#awesome ul li:eq(3)"); isn't so pseudo :-)

Podesta answered 6/1, 2011 at 8:12 Comment(0)
D
3
 $("ul li a").click(function () {
    $(this).parent().insertBefore('ul li:eq(0)');
  });


<ul>
    <li><a>a</a></li>
    <li><a>b</a></li>
    <li><a>c</a></li>
    <li><a>d</a></li>
    <li><a>e</a></li>
    <li><a>f</a></li>
</ul>
Dreary answered 30/4, 2015 at 7:23 Comment(1)
It is removed my values on clickDiabolize

© 2022 - 2024 — McMap. All rights reserved.