我在 div.slider
中有一个 div.slides
列表。使用js,我得到了.slider
内所有.slides
的NodeList
:let slips = document.querySelectorAll('.slider .slide ');
完全没问题(还有 slider 本身 const slider = document.querySelector('.slider');
)。
但是每当我尝试将 .slides
中的最后一个元素添加到 .slider
前面时,它都会删除最后一个 .slider
。
因此,例如,从 a b c
列表中,它应该是 c a b c
,但它变成了 c a b
。
我尝试了 slider.insertBefore(slides[slides.lenght -1, Slides[0]);
slider.appendChild(slides[slides.length - 1]);
以及其他一些。
如何将 nodeList 元素的副本添加到开头/结尾而不删除类似/重复元素?
没有jquery
最佳答案
使用Node.cloneNode() :
slider.insertBefore(slides[slides.lenght -1].cloneNode(), slides[0]);
insertBefore()
和 appendChild()
都将节点移动到新位置而不复制它。
来自Node.insertBefore文档:
If the given node already exists in the document,
insertBefore()
moves it from its current position to the new position. (That is, it will automatically be removed from its existing parent before appending it to the specified new parent.)This means that a node cannot be in two locations of the document simultaneously.
Note: The
Node.cloneNode()
can be used to make a copy of the node before appending it under the new parent. Note that the copies made with cloneNode() will not be automatically kept in sync.
关于javascript - .append 不替换相似元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61638136/