60

What is the best way to reverse the order of child elements with jQuery.

For example, if I start with:

<ul>
  <li>A</li>
  <li>B</li>
  <li>C</li>
</ul>

I want to end up with this:

<ul>
  <li>C</li>
  <li>B</li>
  <li>A</li>
</ul>
tilleryj
  • 14,259
  • 3
  • 23
  • 22
  • are you doing a sorting type of thing? If not you can do something like this http://api.jquery.com/get/ – Matt Mar 18 '11 at 03:50
  • I'm not really sorting here, but I have a separate task that will involve sorting. Thanks for the tip. – tilleryj Mar 18 '11 at 16:52

6 Answers6

141
var list = $('ul');
var listItems = list.children('li');
list.append(listItems.get().reverse());
Anurag
  • 140,337
  • 36
  • 221
  • 257
  • 2
    I never noticed this answer before now, but I'll agree that it's better than my answer. Mine just illustrates an interesting property of append/prepend. – undefined Jul 11 '13 at 17:18
  • Short and sweet. One question: What's the difference between `listItems.reverse();` and `listItems.get().reverse()`? I don't understand why the first one doesn't work, isn't ListItems an array of `
  • ` elements?
  • – M - Aug 04 '14 at 19:48
  • 3
    listItems is an instance of the jQuery object which wraps an array of DOM elements. It isn't a regular array why is why we call get() on it to get back a plain array which we know can be reversed. – Anurag Aug 04 '14 at 20:41
  • 1
    @tfmontague - Do you have performance benchmarks to prove that? – Anurag Oct 27 '14 at 23:25
  • @Anurag - I've retracted my earlier statement. Benchmarks show that list.prepend() and list.append() have faster performance than list.html() - http://jsperf.com/reversehtmlvsappend – tim-montague Oct 28 '14 at 08:50
  • @tfmontague - yeah though it's only marginally faster. I wouldn't care about the differences.. – Anurag Oct 28 '14 at 18:11
  • Performance is the least of the issues with `.html()` - you should _never_ use `.html` or anything else that serialises the DOM and then deserialises it again just to move elements. That's what node objects are for! – Alnitak Dec 27 '14 at 21:20
  • 1
    I disagree with that statement. If using `.html()` *somehow* turned out to be noticeably faster than reordering node elements and your application demands performance and this element reorder is a bottleneck, then by all means please go ahead and use `html()`. The reason I would prefer *not* to use `html()` is because of incorrectness. `html()` will recreate all those elements from scratch and any state that is not serialized such as event handlers will get lost. So it won't simply be a reorder operation anymore but a slightly more destructive operation with other side-effects. – Anurag Dec 30 '14 at 04:53