guub guub - 4 days ago 4
jQuery Question

Order elements using index number

How can I re-order elements using index number?

For example if I have a list

<ul>
<li data-name="tree"></li>
<li data-name="park"></li>
<li data-name="house"></li>
<li data-name="fountain"></li>
</ul>


How can I move 'house' to 1st place using number?
I can get the zero-based index for a list item by using
index()
, but I can't move the element to a specific index.

Example:

$("[data-name='house']").moveTo(1);

Answer

Here's a snippet that may help. The offset supplied to moveTo is the position (0=first) to insert the element among the remaining children. Solutions that depend on insertBefore or similar functions are simpler, but this version of moveTo should work for moving the element to any position (including before the first or after the last child) and should handle the special case where you move an only child to position zero without causing an error.

$.fn.moveTo = function(i) {
    var p = this.parent()
    var c = this.detach()
    var cs = p.children()
    cs = [].concat(cs.slice(0,i), c.get(), cs.slice(i))
    p.html(cs)
}

var i = 0;
var next = function() {
  if (++i > 3) { i = 0 }
  $('[data-name="tree"]').moveTo(i)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
   <li data-name="tree">tree</li>
   <li data-name="park">park</li>
   <li data-name="house">house</li>
   <li data-name="fountain">fountain</li>
</ul>
<button onclick="next()">Move</button>

Comments