guub guub - 1 year ago 61
jQuery Question

Order elements using index number

How can I re-order elements using index number?

For example if I have a list

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

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



Answer Source

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))

var i = 0;
var next = function() {
  if (++i > 3) { i = 0 }
<script src=""></script>
   <li data-name="tree">tree</li>
   <li data-name="park">park</li>
   <li data-name="house">house</li>
   <li data-name="fountain">fountain</li>
<button onclick="next()">Move</button>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download