'remove'和'removeChild'方法有什么区别是javascript?

Pra*_*oon 4 html javascript

我创建了一个HTML页面来了解删除元素的工作原理.

代码:

<html>
  <head>
    <script>
      var childDiv = null;
      var parent1 = null;
      var parent2 = null;
      function init() {
        childDiv = document.getElementById("child");
        parent1 = document.getElementById("parent1");
        parent2 = document.getElementById("parent2");
      }

      function rem() {
        if (childDiv) {
          childDiv.remove();
          alert("child removed");
        } else {
          alert("child does not exist");
        }
      }

      function remChild() {
        if (childDiv){
          if (parent1.children.length > 0) {
            parent1.removeChild(childDiv);
            alert("child unbound from parent");
          } else {
            alert("child exists but is not bound to parent");
          }
        } else {
          alert("child does not exist");

        }
      }

      function ins() {
        if (childDiv) {
          parent2.appendChild(childDiv);

          alert("child inserted to another parent");
        }
      }
    </script>
  </head>
  <body onload="init()">
    <div id="parent1">
      <div id="child"></div>
    </div>
    <div id="parent2"></div>
    <button onclick="rem()">remove</button>
    <button onclick="remChild()">removeChild</button>
    <button onclick="ins()">insert</button>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

在这里,我尝试以两种方式删除'child'div:

  1. 通过在'child' div上调用'remove'方法

  2. 通过在'parent1'节点上调用'removeChild'方法

但在这两种情况下,节点实际上都没有被删除.我总是可以将'child'div插入'parent2'.

我可以理解,在第二种情况下,'child'从'parent1'解除绑定,而不是实际删除.但在第一种情况下,"孩子"是不是永久删除了?

尝试插入不存在的元素时,我不应该收到错误吗?

请解释.

如果元素在元素上调用'remove'之后确实存在:

  1. 如何'删除'与'removeChild'不同?正如我所看到的,这两种方法都只是来自父节点的未绑定子节点,但元素仍占用内存.

  2. 有没有办法确保元素实际从内存中删除?

Ori*_*iol 12

该节点实际上并未删除

混淆可能是因为您可能认为删除元素意味着杀死或破坏它.

在此输入图像描述

但实际上,删除的概念基本上意味着打破了孩子与其父母之间的关系.这只是一个分离.

在此输入图像描述

尝试插入不存在的元素时,我不应该收到错误吗?

不,因为它仍然存在.

有什么remove不同removeChild

remove只需要提到孩子.removeChild需要父母和孩子的参考.结果是一样的.

有没有办法确保元素实际从内存中删除?

不可以.你只能不引用它,并希望有一个垃圾收集器,它将检测到没有引用的对象,然后将其删除.


Den*_*ret 8

remove是一个新功能。这是一个快捷方式,可以更轻松地删除元素而无需查找父节点。不幸的是,它在旧版本的 Internet Explorer 上不可用,因此,除非您不想支持此浏览器,否则您必须使用removeChild或使用polyfill

子元素保留在内存中的原因是您的代码保留对它的引用。

如果你这样做

childDiv = null;
Run Code Online (Sandbox Code Playgroud)

那么就没有指向它的引用,浏览器可以释放内存。