一组元素的反向顺序

use*_*293 11 html javascript jquery

我有一组看起来像这样的div:

<div id="con">
    <div> 1 </div>
    <div> 2 </div>
    <div> 3 </div>
    <div> 4 </div>
    <div> 5 </div>
</div>
Run Code Online (Sandbox Code Playgroud)

但我想让它们翻转,看起来像这样:

<div> 5 </div>
<div> 4 </div>
<div> 3 </div>
<div> 2 </div>
<div> 1 </div>
Run Code Online (Sandbox Code Playgroud)

因此,当添加div时,它将转到列表的末尾....

我怎么能这样做(或者有更好的方法)?

Phr*_*ogz 16

作为一个很好的jQuery函数包装在任何选择集上:

$.fn.reverseChildren = function() {
  return this.each(function(){
    var $this = $(this);
    $this.children().each(function(){ $this.prepend(this) });
  });
};
$('#con').reverseChildren();
Run Code Online (Sandbox Code Playgroud)

证明:http://jsfiddle.net/R4t4X/1/

编辑:修复以支持任意jQuery选择


Chr*_* K. 10

我发现以上所有内容都令人不满意。这是一个香草 JS 单线:

parent.append(...Array.from(parent.childNodes).reverse());  
Run Code Online (Sandbox Code Playgroud)

带解释的片段:

parent.append(...Array.from(parent.childNodes).reverse());  
Run Code Online (Sandbox Code Playgroud)
// 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);
Run Code Online (Sandbox Code Playgroud)


Aym*_*man 9

一个vanilla JS解决方案:

function reverseChildren(parent) {
    for (var i = 1; i < parent.childNodes.length; i++){
        parent.insertBefore(parent.childNodes[i], parent.firstChild);
    }
}
Run Code Online (Sandbox Code Playgroud)


Sax*_*ier 6

没有图书馆:

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'));
Run Code Online (Sandbox Code Playgroud)

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();
Run Code Online (Sandbox Code Playgroud)

jsPerf测试