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());
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.
Try this:
$(function() {
$.fn.reverse = [].reverse;
var x = $('li');
$('ul').empty().append(x.reverse());
});
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