我看到了这个例子并试图理解html背后的理论 如果我在
中使用 class 和 id 为什么它不起作用。为什么我无法删除它给我错误的子元素
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<script>
window.onload = function() {
var parent = document.getElementsByClassName("demo");
var child = document.getElementById("p1");
parent.removeChild(child);
};
</script>
</head>
<body>
<div class="demo">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
</body>
</html>
但是如果我索引父节点它就可以工作!我想知道它是如何工作的
var parent =document.getElementById("p1");
parent[0].removeChild(child);
最佳答案
此处,更正为选择单个元素。
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<script>
window.onload = function() {
var parent = document.querySelector(".demo");
var child = parent.querySelector("#p1");
parent.removeChild(child);
};
</script>
</head>
<body>
<div class="demo">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
</body>
</html>
关于javascript - 从父级中删除子级时使用类和id的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55056052/