Обратный порядок набора элементов
У меня есть набор div, который выглядит так:
<div id="con">
<div> 1 </div>
<div> 2 </div>
<div> 3 </div>
<div> 4 </div>
<div> 5 </div>
</div>
Но я хочу, чтобы они перевернули так, чтобы он выглядел так:
<div> 5 </div>
<div> 4 </div>
<div> 3 </div>
<div> 2 </div>
<div> 1 </div>
Итак, когда добавляется div, он перейдет в конец списка.
Как я могу это сделать (или есть лучший способ сделать это)?
Ответы
Ответ 1
Завершена как хорошая функция jQuery, доступная для любого набора параметров:
$.fn.reverseChildren = function() {
return this.each(function(){
var $this = $(this);
$this.children().each(function(){ $this.prepend(this) });
});
};
$('#con').reverseChildren();
Доказательство: http://jsfiddle.net/R4t4X/1/
Изменить: исправлено для поддержки произвольных выборов jQuery
Ответ 2
Ванильное решение JS:
function reverseChildren(parent) {
for (var i = 1; i < parent.childNodes.length; i++){
parent.insertBefore(parent.childNodes[i], parent.firstChild);
}
}
Ответ 3
без библиотеки:
function reverseChildNodes(node) {
var parentNode = node.parentNode, nextSibling = node.nextSibling,
frag = node.ownerDocument.createDocumentFragment();
parentNode.removeChild(node);
while(node.lastChild)
frag.appendChild(node.lastChild);
node.appendChild(frag);
parentNode.insertBefore(node, nextSibling);
return node;
}
reverseChildNodes(document.getElementById('con'));
JQuery-стиль:
$.fn.reverseChildNodes = (function() {
function reverseChildNodes(node) {
var parentNode = node.parentNode, nextSibling = node.nextSibling,
frag = node.ownerDocument.createDocumentFragment();
parentNode.removeChild(node);
while(node.lastChild)
frag.appendChild(node.lastChild);
node.appendChild(frag);
parentNode.insertBefore(node, nextSibling);
return node;
};
return function() {
this.each(function() {
reverseChildNodes(this);
});
return this;
};
})();
$('#con').reverseChildNodes();
jsPerf Test
Ответ 4
Один из способов:
function flip(){
var l=$('#con > div').length,i=1;
while(i<l){
$('#con > div').filter(':eq(' + i + ')').prependTo($('#con'));
i++;
}
}
Ответ 5
Я нашел все вышеперечисленное как-то неудовлетворительно. Вот одна ваниль JS:
parent.append(...Array.from(parent.childNodes).reverse());
Фрагмент с пояснениями:
// Get the parent element.
const parent = document.getElementById('con');
// Shallow copy to array: get a 'reverse' method.
const arr = Array.from(parent.childNodes);
// 'reverse' works in place but conveniently returns the array for chaining.
arr.reverse();
// The experimental (as of 2018) 'append' appends all its arguments in the order they are given. An already existing parent-child relationship (as in this case) is "overwritten", i.e. the node to append is cut from and re-inserted into the DOM.
parent.append(...arr);
<div id="con">
<div> 1 </div>
<div> 2 </div>
<div> 3 </div>
<div> 4 </div>
<div> 5 </div>
</div>
Ответ 6
Другой (более простой?) ванильный ответ javascript: http://jsfiddle.net/d9fNv/
var con = document.getElementById('con');
var els = Array.prototype.slice.call(con.childNodes);
for (var i = els.length -1; i>=0; i--) {
con.appendChild(els[i]);
}
Альтернативно, более короткий, но менее эффективный метод: http://jsfiddle.net/d9fNv/1/
var con = document.getElementById('con');
Array.prototype.slice.call(con.childNodes).reverse().forEach(function(el) {
con.appendChild(el);
});