javascript - 从父级中删除子级时使用类和id的问题

标签 javascript html

我看到了这个例子并试图理解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/

相关文章:

javascript - 如何正确获取文本区域内容?

javascript - jQuery 多个可选择的列表项组

php - 如果取消选中一个单选按钮,会显示错误吗?

javascript - 从 Javascript 加载一些文件

html - 无法对齐内联 block 图像和导航按钮

Javascript 动画无法正常运行

javascript - 如何在node.js中获取网络静态信息,例如Rx/Tx字节(/数据包)

php - jQuery 将动态元素 id/值传递到 PHP

javascript - jQuery 已弃用同步 XMLHTTPRequest

javascript - 从 api 调用中检索 ng-options 的值