<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>DOM节点操作(增、删、改、替换、克隆</title>
<style>
#box1 {
width: 100px;
height: 100px;
background: red;
border: 2px solid #000;
}
</style>
</head>
<body>
<div id="box">
<p>我是p标签</p>
<div id="div1"></div>
<div id="box1">
<div>这是一个div</div>
</div>
</div>
<div id="box2">
<div id="div2"></div>
<div id="div3"></div>
</div>
<script>
//创建节点
{
/*
element createElement("tagName"); //创建元素
*/
let h1 = ("h1");
= "我是标题";
(h1); //打印:<h1>我是标题</h1>
}
//尾部添加节点
{
/*
(node); 向 parent 插入 node,插入在 node 的内容的最末尾
*/
let box = ("#box");
let h1 = ("h1");
= "我是标题";
(h1); //页面上展示:我是标题
}
//头部添加节点
{
/*
(newNode,oldNode); 在 parent 插入 newNode,插入在 oldNode 之前
如果插入的节点是一个已有节点的话,会先把这个节点,从原先的位置删除,然后放入我们的新位置
*/
let box = ("#box");
let p = ("p")
let h1 = ("h1");
= "我插在p标签之前";
(h1,p)
}
//替换节点
{
/*
(newNode,oldNode),newNode替换oldNode
如果插入的节点是一个已有节点的话,会先把这个节点,从原先的位置删除,然后放入我们的新位置
*/
let box = ("#box");
let div1 = ("#div1");
let div2 = ("#div2")
(div2,div1) //节点div1被替换为div2
}
//删除节点
{
let box = ("#box");
let box2 = ("#box2");
let div2 = ("#div2");
let div3 = ("#div3");
// () 把 node 从 DOM 中删除
(()); //打印:undefined 删除div2,返回值为undefined
// (node) 从 parent 删除掉 node 节点
((div3)); //打印:<div id="div3"></div> 删除div3,返回被删除的DOM元素
}
//克隆节点
{
//(bool=false) 默认为false浅克隆,true为深度克隆
let box = ("#box");
let box1 = ("#box1");
= function(){
alert(1);
}
((true));
}
</script>
</body>
</html>