【问题标题】:Using removeChild with HTMLCollection将 removeChild 与 HTMLCollection 一起使用
【发布时间】:2023-03-04 00:27:02
【问题描述】:

考虑这段代码:

xr = document.querySelectorAll('.material-tooltip'); // NodeList
console.log(xr.length); // 50
for (ya of xr)
  ya.parentNode.removeChild(ya);
zu = document.querySelectorAll('.material-tooltip');
console.log(zu.length); // 0

这按预期工作,它删除了所有找到的元素。现在考虑这个 代码:

xr = document.getElementsByClassName('material-tooltip'); // HTMLCollection
console.log(xr.length); // 50
for (ya of xr)
  ya.parentNode.removeChild(ya);
zu = document.getElementsByClassName('material-tooltip');
console.log(zu.length); // 25

它只删除了找到的元素的一半。这是什么原因造成的?

【问题讨论】:

标签: javascript removechild getelementsbyclassname nodelist htmlcollection


【解决方案1】:

querySelectorAll 返回非实时NodeListgetElementsByClassName 返回直播 HTMLCollection。前者的行为类似于任何数组:您遍历数组,然后为每个元素做一些事情。但是一个直播的HTMLCollection就不同了——它的内容随时反映了DOM中的当前情况;如果你从 DOM 中移除一个元素,它会在 xr 中消失,如果你向 DOM 添加一个适合选择器的元素,它会出现在 xr 中,即使在你运行 getElementsByClassName 之后 .

让我们将ya 的第一次迭代变为0。您删除了xr[0]它会从列表中消失。现在元素 1 是xr[0]ya 变为 1;然后删除xr[1](元素2),跳过元素1。然后删除 xr[2](元素 3),并跳过元素 4...等等。

每当您在直播 HTMLCollection 上进行操作时,要么从后向前走,这样消失的元素就不会弄乱你,要么克隆 HTMLCollection 以将其元素固定到位,或者只是执行一个循环删除xr[0] 直到 xr 为空。

【讨论】:

  • 更短的while (xr[0]) xr[0].parentNode.removeChild(xr[0])
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-19
  • 1970-01-01
  • 2014-06-08
  • 1970-01-01
相关资源
最近更新 更多