Moving a DIV element to bottom of parent (as last child)

喜欢而已 提交于 2019-12-05 15:44:46

问题


I'm trying to create a continually rotating banner for the top of the homepage of a site I'm developing. The best way that I can figure to keep it constantly in rotation is to take the first DIV (firstChild) and move it to the end of the stack once it's slid out of view.

This:

<div id='foo0'></div>
<div id='foo1'></div>
<div id='foo2'></div>
<div id='foo3'></div>

Should become this:

<div id='foo1'></div>
<div id='foo2'></div>
<div id='foo3'></div>
<div id='foo0'></div>

I use the Prototype framework... and I've tried to do this by cloning the element using my own method and inserting it into the bottom of the parent DIV, but I find that not all of the style attributes are being carried over, and I'd like to abandon this method because I don't want what's being moved to be a copy/clone of the element, but the actual element itself.

Thanks.


回答1:


Here's some plain javascript to do it, assuming the div has a valid parent:

var d = document.getElementById('foo0');
d.parentNode.appendChild(d);

Essentially you get the node, then append it to its parent. appendChild, if the node is already part of the DOM, will move the node from its current position to the new position in the DOM.




回答2:


wrap your divs with a parent div:

    var parentElement =  document.querySelector("#yourParentDiv");
    parentElement.appendChild(parentElement.firstElementChild);


来源:https://stackoverflow.com/questions/3415480/moving-a-div-element-to-bottom-of-parent-as-last-child

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!