How to sort DOM elements by jQuery?

Question:

Suppose I have the following list:

<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
</ul>

I want all even numbered elements to be sorted so that the even numbers are first and the odd numbers last.

So:

<ul>
  <li>2</li>
  <li>4</li>
  <li>1</li>
  <li>3</li>
</ul>

How could I do this via jQuery ?

Answer:

It depends a little on how you are going to compare the elements. Using index , ie their position you could do like this:

var secundario = [];

$('ul li').each(function(i){
    if (i % 2 != 0) return;
    var removido = $(this).remove();
    secundario.push(removido);
});
$('ul').append(secundario);

This removes the elements that shouldn't be there, saves them in a separate array and at the end puts them back. The if (i % 2 != 0) part is to know if the i is even or odd. If the position/index is even, it does nothing.

Example: http://jsfiddle.net/7dt1b0nf/

If you want to use .innertHTML you can use var i = this.innerHTML; (with parseInt it would be even more correct) and then if (i % 2 == 0) return; like this: (example) .

The same code without jQuery would look like this:

(function () {
    var secundarios = [];
    var ul = document.querySelector('ul');
    var lis = ul.querySelectorAll('li');
    [].forEach.call(lis, function (el, i) {
        if (i % 2 != 0) return;
        var removido = ul.removeChild(el);
        secundarios.push(removido);
    });
    [].forEach.call(secundarios, function (el) {
        ul.appendChild(el);
    });
})();

Example: http://jsfiddle.net/7dt1b0nf/5/

If it is important to order, it can be done like this:

select all and iterate > split even/odd > sort each > rejoin in DOM.

JavaScript

(function () {
    function ordenar(a, b) {
        return parseInt(a.innerHTML, 10) > parseInt(b.innerHTML, 10);
    }

    var ul = document.querySelector('ul');
    var lis = ul.querySelectorAll('li');
    var impares = [];
    var pares = [];
    [].forEach.call(lis, function (el) {
        var nr = parseInt(el.innerHTML, 10);
        if (nr % 2 == 0) pares.push(el);
        else impares.push(el);
        ul.removeChild(el);
    });
    [pares, impares].forEach(function (arr) {
        arr.sort(ordenar).forEach(function (el) {
            ul.appendChild(el);
        });
    });
})();

example: http://jsfiddle.net/722w1dcg/

Scroll to Top