javascript - 循环使用 '.remove()'删除节点,为什么所有节点都不会被删除

标签 javascript

<!DOCTYPE HTML>
<html>
<head>
  <meta charset="utf-8">
</head><body>

<style>
.alert {
  padding: 15px;
  border: 1px solid #d6e9c6;
  border-radius: 4px;
  color: #3c763d;
  background-color: #dff0d8;
}
</style>

<script>
  let div = document.createElement('div');
  let div1 = document.createElement('div');
  let div2 = document.createElement('div');
  let div3 = document.createElement('div');
  
  div.className = "alert alert-success";
  div1.className = "alert alert-success";
  div2.className = "alert alert-success";
  div3.className = "alert alert-success";
  
  div.innerHTML = "<strong>Hi there!</strong> You've read an important message.";
  div1.innerHTML = "<strong>Hi there!1</strong> You've read an important message.";
  div2.innerHTML = "<strong>Hi there!2</strong> You've read an important message.";
  div3.innerHTML = "<strong>Hi there!3</strong> You've read an important message.";
  
  document.body.append(div);
  document.body.append(div1);
  document.body.append(div2);
  document.body.append(div3);
  
  let divs = document.getElementsByTagName('div');
  for(let x of divs){
    x.remove();  
  }
  
</script>

</body>
</html>

最近在学JS,遇到一个问题。 我想所有的“div”都会被删除, 但 div1 和 div3 仍然存在.... 不知道为什么,求助 并解释为什么会这样? 提前致谢。

最佳答案

我相信getElementsByTagName返回的不是数组,而是一个实时 HTML 集合。
集合本身被 remove() 方法改变,这会导致意外行为。

解决方案:在循环之前将其转换为数组

let div = document.createElement('div');
let div1 = document.createElement('div');
let div2 = document.createElement('div');
let div3 = document.createElement('div');

div.className = "alert alert-success";
div1.className = "alert alert-success";
div2.className = "alert alert-success";
div3.className = "alert alert-success";

div.innerHTML = "<strong>Hi there!</strong> You've read an important message.";
div1.innerHTML = "<strong>Hi there!1</strong> You've read an important message.";
div2.innerHTML = "<strong>Hi there!2</strong> You've read an important message.";
div3.innerHTML = "<strong>Hi there!3</strong> You've read an important message.";

document.body.append(div);
document.body.append(div1);
document.body.append(div2);
document.body.append(div3);

var divs = document.getElementsByTagName('div');
for(let x of Array.from(divs)) {
  console.log(x.innerHTML);
  x.remove();
}
.alert {
  padding: 15px;
  border: 1px solid #d6e9c6;
  border-radius: 4px;
  color: #3c763d;
  background-color: #dff0d8;
}

关于javascript - 循环使用 '.remove()'删除节点,为什么所有节点都不会被删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49777255/

相关文章:

javascript - 使用node.js在AWS Elasticsearch中建立索引时如何放置其他设置

javascript - 为什么服务器不应该使用 JSON 数组进行响应?

javascript - 如何保留对 RequireJS 模块的引用?

javascript - 修复 Angular 中的循环依赖

javascript - 在对象内插入按钮?

javascript - 在 TypeScript 中为 'export' 赋值意味着什么?

javascript - 在异步等待中返回未决的 promise

php - 使用 XMLHttprequest 上传多个文件

javascript - 如何在不剪切内容的情况下减小 iframe 的大小?

javascript - 鼠标悬停时更改图像的通用函数