How to sort elements of the DOM by jQuery?

6

Suppose I have the following list:

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

I want all elements of even numbers to be ordered, so that the pairs are first, and the odd ones, finally.

So:

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

How could I do this via jQuery ?

    
asked by anonymous 11.08.2015 / 16:08

3 answers

7

It depends a little on how you compare the elements. Using index , that is the position of them 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 should not be there, save them in a separate array, and then put them back in. The if (i % 2 != 0) part is to know if i is even or odd. If the position / index is even, it does nothing.

Example: link

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

The same jQuery-free 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: link

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

  

select all and iterate > split in even / odd > sort each > rejoin the 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: link

    
11.08.2015 / 16:14
2

It follows another possibility, only without jQuery and based on a random list.

var lista = document.querySelector("ul");
var itens = lista.querySelectorAll("li");

itens = [].slice.apply(itens);

//ordernar os itens de forma ascedente
itens.sort(function (itemA, itemB) {    
    return parseInt(itemA.innerHTML) > parseInt(itemB.innerHTML);
});

//ordernar os itens de forma a listar os numeros pares primeiro.
itens.sort(function (itemA, itemB) {    
    return parseInt(itemA.innerHTML) % 2 > parseInt(itemB.innerHTML) % 2;
});

//atualizar a ordem da lista 
//P.S: não há a necessidade de remover o elemento de forma previa.
itens.forEach(function (item) {   
    lista.appendChild(item);
});
<ul>
  <li>4</li>
  <li>1</li>  
  <li>3</li>
  <li>7</li>  
  <li>2</li>  
  <li>6</li>  
  <li>9</li>  
</ul>
    
11.08.2015 / 18:55
1

You can do this in order to get the ordering you want:

$(function() {
    var elems = $('ul').children('li').remove();
        //ordena sua lista em ordem crescente
       elems.sort(function(a, b) {
         return (parseInt($(a).text()) > parseInt($(b).text()));
    })
       /* separa primeiro os pares em forma
          ordenada e mantém na sequência da lista os ímpares */
      .sort(function(a, b) {
        var numB = parseInt($(b).text());
        var numA = parseInt($(a).text());
         return (numB % 2 == 0 && (numB % 2 < numA % 2));
    });
    $('ul').append(elems);
});
Here's the example: link     
11.08.2015 / 17:42