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.
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);
});
})();
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);
});
});
})();
Who gave the
-1
can also comment. I always think it is good to exchange ideas and know what you think is wrong.– Sergio
Everyone suffers one day with the -1 ghost.
– Wallace Maxters