【问题标题】:Javascript removeChild not removing all elements inside loopJavascript removeChild 没有删除循环内的所有元素
【发布时间】:2021-05-15 21:48:17
【问题描述】:

我想做什么 -

  1. 通过javascript从DOM中获取特定类的所有元素
  2. 从元素的父级获取img元素
  3. 在父元素之前插入img 元素
  4. 移除父元素

代码如下:

let elms = el.getElementsByClassName("my-class");
console.log(elms) // 6 elements are printed here
for (let elm of elms) {
    console.log("Inside loop") //only printed 3 times
    let elm_parent = elm.parentNode;
    let img_elm = elm_parent.getElementsByTagName("img");
    elm.parentNode.parentNode.insertBefore(img_elm[0], elm_parent);
    elm.parentNode.parentNode.removeChild(elm_parent);
} 
//Loop only executes 3 times

这是 HTML 的结构(总共有 6 个这样的元素):

<p>
    <div style="position: relative; display: block;">
        <img src="http://something.com/image1" style="display: block;">
        <div></div><svg class="my-class" viewBox="0 0 341 102">
            <g>
                <g class="a9s-selection" style="pointer-events: none;">
                    <rect class="outer" x="-1.5" y="58" width="147" height="40"></rect>
                    <rect class="inner" x="-1.5" y="58" width="147" height="40"></rect>
                </g>
            </g>
        </svg>
    </div>
    <br>
</p>

如您所见,虽然elms 有6 个元素,但循环只执行了3 次。谁能帮我理解为什么会这样?

【问题讨论】:

  • 你能分享一下你的html结构吗?
  • @AlanOmar 完成...
  • getElementsByClassName 返回元素的实时集合,这会扰乱迭代。不要在任何地方使用.getElementsBy*,而是使用.querySelectorAll
  • @Teemu 使用querySelectorAll 解决了这个问题。非常感谢!

标签: javascript html vue.js dom


【解决方案1】:

问题:对象的引用调用。

当您执行el.getElementsByClassName("my-class"); 时,它会为您提供一个看起来像数组的实时HTMLCollection 对象。由 DOM 本身处理。 如果您从 DOM 中删除 HTMLCollection 中存在的任何内容,则该 HTMLCollection 的长度也会减少。

解决方案:以数组的形式创建HTMLCollection 的副本。

let elms = el.getElementsByClassName("my-class");
elms = Array.from(elms);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-27
    • 2023-04-09
    • 2020-05-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-19
    相关资源
    最近更新 更多