<!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/