for循环中的克隆元素中断并永远运行
Cloning element in for loop breaks and runs forever
我想获取所有具有特定 class 的元素 (svgs
) 并将它们克隆到 div.
中
const images = document.getElementsByClassName('image_svg'); // collection of all elements (around 5 or so of them)
const myDiv = document.getElementsByClassName('myDiv')[0];
for (let i = 0; i < images.length; i++) {
var clone = images[i].cloneNode(true);
myDiv.appendChild(clone);
}
当我执行我的代码时,它永远运行并且浏览器停止响应。我在这里做错了什么?
注意,这是一个纯 JS 解决方案,所以没有 jQuery 个答案。
原因是getElementsByClassName()
returns一个live合集
试试 Document.querySelectorAll()
and Document.querySelector()
The Document method querySelectorAll()
returns a static (not live) NodeList representing a list of the document's elements that match the specified group of selectors.
The Document method querySelector()
returns the first Element within the document that matches the specified selector, or group of selectors. If no matches are found, null is returned.
const images = document.querySelectorAll('.image_svg'); // collection of all elements (around 5 or so of them)
const myDiv = document.querySelector('.myDiv');
我想获取所有具有特定 class 的元素 (svgs
) 并将它们克隆到 div.
const images = document.getElementsByClassName('image_svg'); // collection of all elements (around 5 or so of them)
const myDiv = document.getElementsByClassName('myDiv')[0];
for (let i = 0; i < images.length; i++) {
var clone = images[i].cloneNode(true);
myDiv.appendChild(clone);
}
当我执行我的代码时,它永远运行并且浏览器停止响应。我在这里做错了什么?
注意,这是一个纯 JS 解决方案,所以没有 jQuery 个答案。
原因是getElementsByClassName()
returns一个live合集
试试 Document.querySelectorAll()
and Document.querySelector()
The Document method
querySelectorAll()
returns a static (not live) NodeList representing a list of the document's elements that match the specified group of selectors.The Document method
querySelector()
returns the first Element within the document that matches the specified selector, or group of selectors. If no matches are found, null is returned.
const images = document.querySelectorAll('.image_svg'); // collection of all elements (around 5 or so of them)
const myDiv = document.querySelector('.myDiv');