JavaScript moving element in the DOM

后端 未结 7 1677
囚心锁ツ
囚心锁ツ 2020-11-27 12:25

Let\'s say I have three

elements on a page. How can I swap positions of the first and third
? jQuery is fine.

7条回答
  •  清歌不尽
    2020-11-27 12:41

    var swap = function () {
        var divs = document.getElementsByTagName('div');
        var div1 = divs[0];
        var div2 = divs[1];
        var div3 = divs[2];
    
        div3.parentNode.insertBefore(div1, div3);
        div1.parentNode.insertBefore(div3, div2);
    };
    

    This function may seem strange, but it heavily relies on standards in order to function properly. In fact, it may seem to function better than the jQuery version that tvanfosson posted which seems to do the swap only twice.

    What standards peculiarities does it rely on?

    insertBefore Inserts the node newChild before the existing child node refChild. If refChild is null, insert newChild at the end of the list of children. If newChild is a DocumentFragment object, all of its children are inserted, in the same order, before refChild. If the newChild is already in the tree, it is first removed.

提交回复
热议问题