jquery 一组HTML元素的逆序

oxf4rvwz  于 2023-10-17  发布在  jQuery
关注(0)|答案(8)|浏览(129)

我有一组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>时,它会转到列表的末尾。
我该怎么做(或者有没有更好的方法)?

q7solyqu

q7solyqu1#

一个vanilla JS解决方案:

function reverseChildren(parent) {
    for (var i = 1; i < parent.childNodes.length; i++){
        parent.insertBefore(parent.childNodes[i], parent.firstChild);
    }
}
kpbwa7wx

kpbwa7wx2#

作为一个很好的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选择

dnph8jn4

dnph8jn43#

我发现上面的一切都不令人满意。下面是一个vanilla JS一行程序:

parent.append(...Array.from(parent.childNodes).reverse());

带解释的sniffing:

// 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>
anauzrmj

anauzrmj4#

没有图书馆:

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

vecaoik1

vecaoik15#

单程:

function flip(){
 var l=$('#con > div').length,i=1;
 while(i<l){
   $('#con > div').filter(':eq(' + i + ')').prependTo($('#con'));
   i++;
 }
}
mv1qrgav

mv1qrgav6#

更简单(simpler)?)vanilla 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);
});
carvr3hs

carvr3hs7#

我认为最简单的就是使用display: flex

#con {
  display: flex;
  flex-direction: column-reverse;
}
<div id="con">
    <div> 1 </div>
    <div> 2 </div>
    <div> 3 </div>
    <div> 4 </div>
    <div> 5 </div>
</div>
qkf9rpyu

qkf9rpyu8#

const container = document.getElementById("con");
    const divs = Array.from(container.querySelectorAll("div"));
    
    // Reverse the order of the div elements
    divs.reverse();
    
    // Append the reversed divs back to the container
    divs.forEach((div) => {
        container.appendChild(div);
    });
<div id="con">
    <div> 1 </div>
    <div> 2 </div>
    <div> 3 </div>
    <div> 4 </div>
    <div> 5 </div>
    <div> 6 </div>
    <div> 7 </div>
    <div> 0 </div>
</div>

相关问题