How to sort DOM elements by jQuery?

Asked

Viewed 943 times

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 sorted, so that the pairs are first, and the odd ones, last.

Thus:

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

How could I do that jQuery?

3 answers

7


It depends a little on how you compare the elements. Using the index, I mean, their position could do:

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, stores them in a separate array and at the end puts them back. The part if (i % 2 != 0) 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 the .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 code without jQuery would be so:

(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’s important to order it can be done like this:

select all and iterate > split in pair/odd > sort each > re-join 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/

  • 1

    Who gave the -1 can also comment. I always think it is good to exchange ideas and know what you think is wrong.

  • 1

    Everyone suffers one day with the -1 ghost.

2

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>

1

You can do this way that will 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);
});
Follow the example: http://jsfiddle.net/jrHvf/67/

  • and I still hear people say they use jQuery not to pollute the code.

  • but the question asks that it be in Jquery. I do not see pollution in my code, it is clear.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.