DOM学习实用路线(7)——DOM节点操作之替换节点和删除节点

节点操作



替换节点


node.replaceChild(newnode,oldnode)方法用新节点替换某个子节点。
  这个新节点可以是文档中某个已存在的节点,或者您也可创建新的节点。
  用newnode替换 oldChild 的新节点。如果该节点已经存在于 DOM 树中,则它首先会被从原始位置删除。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
<div id="box">
    <div id="div1"></div>
</div>   
<div id="box2">
    <div id="div2"></div>
</div>   
<script>
{
    let box = document.querySelector("#box");
    let div1 = document.querySelector("#div1");
    let h1 = document.createElement("h1");
    h1.innerHTML = "这是一个新节点";
    console.log(box.replaceChild(h1,div1));
}
</script>
</body>
</html>

在这里插入图片描述
  它的返回值是替换掉的旧节点。
在这里插入图片描述


  如果插入的节点是一个已有节点的话,会先把这个节点,从原先的位置删除,然后放入我们的新位置。

let box = document.querySelector("#box");
let div1 = document.querySelector("#div1");
let div2 = document.querySelector("#div2")
let h1 = document.createElement("h1");
h1.innerHTML = "这是一个新节点";
//console.log(box.replaceChild(h1,div1));
box.replaceChild(div2,div1)

在这里插入图片描述

删除节点

  • node.remove() 把 node 从 DOM 中删除
  • parent.removeChild(el) 删除掉某个子元素
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
<div id="box1">
    <div id="div1"></div>
</div>
<div id="box2">
    <div id="div2"></div>
</div> 
<script>
    {
        let box1 = document.querySelector("#box1");
        let div1 = document.querySelector("#div1");
        console.log(div1.remove());  // 返回值为undefined
    }
</script>  
</body>
</html>

node.remove() 把 node 从 DOM 中删除,返回值为undefined。
在这里插入图片描述


parent.removeChild(node) 从 parent 删除掉 node 节点

let box1 = document.querySelector("#box1");
let div1 = document.querySelector("#div1");
//console.log(div1.remove());
console.log(box1.removeChild(div1));

在这里插入图片描述
parent.removeChild(node)返回值是被删除的节点。
在这里插入图片描述
  溜_x_i_a_o_迪童鞋建议使用removeChild,因为兼容性更好,可返回被删节点!




(后续待补充)

发布了34 篇原创文章 · 获赞 12 · 访问量 2525

猜你喜欢

转载自blog.csdn.net/u013946061/article/details/105422397