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