views:

82

answers:

2

How to excange location to childrens of same parent?
I solve using this pattern of code. Is there an easier way? For example something like this: $("#id1").exchange($("#id2"));

<!DOCTYPE html>
    <html>
    <head>
      <style>
      button { display:block; margin:3px; color:red; width:200px; }
      </style>
      <script src="http://code.jquery.com/jquery-latest.min.js"&gt;&lt;/script&gt;
    </head>
    <body>
    <h1>Exchange places</h1>
    <ul>
     <li id="a">a</li>
     <li id="b">b</li>
     <li id="c">c</li>
     <li id="d">d</li>
    </ul>
    <button>exchange 1st,2nd</button>
    <button>exchange 1st,4th</button>
    <button>exchange 2nd,3rd</button>
    <script>

        $("button:first").click(function () {
          var cp = $("li:eq(0)").clone();
          $("li:eq(0)").replaceWith($("li:eq(1)").clone());
          $("li:eq(1)").replaceWith(cp);
        });

        $("button:eq(1)").click(function () {
          var cp = $("li:eq(0)").clone();
          $("li:eq(0)").replaceWith($("li:eq(3)").clone());
          $("li:eq(3)").replaceWith(cp);
        });

        $("button:last").click(function () {
          var cp = $("li:eq(1)").clone();
          $("li:eq(1)").replaceWith($("li:eq(2)").clone());
          $("li:eq(2)").replaceWith(cp);
        });
    </script>

    </body>
    </html>
+1  A: 

You should consider using .sortable() with Jquery UI. No useless buttons, way easier to manipulate.

Take a look

Coronier
Thank you for replying. In my project, li elements are div elements with a link "move up" "move down". For my situation I really do not need an extra 'plug-in' for do excanges since I don't need drag features.
Mattia
A: 

Take a look at SO question 698301. This answer doesn't require cloning or even jQuery; just native DOM manipulation.

Ken Redler