javascript - .append 不替换相似元素

标签 javascript html

我在 div.slider 中有一个 div.slides 列表。使用js,我得到了.slider内所有.slidesNodeList: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/

相关文章:

javascript - 将 JSON 对象添加到 angularjs $scope 中?

html - 图像移到下一行但文本不是

javascript - IE7 中的 HTML5 Doctype 破坏了 Jquery 下拉菜单

javascript - 如何在 JavaScript 中检测并解析这些字符串格式之一?

javascript - 如果innerHTML值等于指定值则停止提交

javascript - 单击 li 时如何使用简单的 javascript 从嵌套跨度中获取文本

javascript - 为什么orientationchange事件在桌面上不触发?

javascript - 根据对象状态在js/html中动态创建按钮

javascript - 更改下拉列表后,我将如何重定向到另一个 URL

JavaScript:替换字符串中最后一次出现的文本