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>
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>
var list = $('ul');
var listItems = list.children('li');
list.append(listItems.get().reverse());
listItems.reverse();
and listItems.get().reverse()
? I don't understand why the first one doesn't work, isn't ListItems an array of <li>
elements?
Aug 4, 2014 at 19:48
.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.
Edit: Anurag's answer is better than mine.
ul = $('#my-ul'); // your parent ul element
ul.children().each(function(i,li){ul.prepend(li)})
If you call .prepend() on an object containing more than one element, the element being appended will be cloned for the additional target elements after the first, so be sure you're only selecting a single element.
$('.many-elements').prepend($('#unique-element')
is going to create copies of the element with id #unique-element. The example above will do this, on a page with multiple ul
elements, but this won't: uls = $('ul'); // all UL elements uls.each(function(i,ul){ $(ul).children().each(function(i,li){$(ul).prepend(li)}) })
Oct 12, 2011 at 0:22
Try this:
$(function() {
$.fn.reverse = [].reverse;
var x = $('li');
$('ul').empty().append(x.reverse());
});
[]
. Wouldn't it be better to use Array.prototype.reverse
instead of [].reverse
?
.empty
is redundant - each element object only exists once and will be automatically removed from its original position in the DOM as its put back into its new position.
All the answer given before me are best but you can try this also
$('#btnrev').click(function(){
$('ul').html($('ul').find('li').get().reverse());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
<button id="btnrev">
click
</button>
Element.prototype.reverse = function(){
var c = [].slice.call(this.children).reverse();
while (this.firstChild) { this.removeChild(this.firstChild); };
c.forEach(function( child ){ this.appendChild(child) }.bind(this))
}
And use like :
document.querySelector('ul').reverse(); // children are now reversed