DOM(Document Object Model)即文档对象模型。通过DOM树这样一种结构,不仅可以直观的看到HTML的整体结构,还可以利用DOM树的一些属性获取到某个元素的子节点和节点名称等信息。
什么是DOM树?
DOM(Document Object Model)即文档对象模型。通过DOM树这样一种结构,不仅可以直观的看到HTML的整体结构,还可以利用DOM树的一些属性获取到某个元素的子节点和节点名称等信息。
HTML文档结构:

树形结构:

childNodes和nodeName属性
childNodes属性:获取当前节点的子节点。
<div id="box">
<p>第一个child节点</p>
<h4>第二个child节点</h4>
<div>第三个child节点</div>
</div>
<script>
let box = document.getElementById("box");
let boxChild = box.childNodes;
console.log(boxChild);
</script>


空格和换行也属于一个节点,用text表示。
for(let i = 1; i < boxChild.length; i += 2)
console.log(boxChild[i]);

获取1、3、5……奇数节点。
nodeName属性:返回节点名称。
for(let i = 1; i < boxChild.length; i += 2)
console.log(boxChild[i].nodeName);

appendChild方法
appendChild(node):在子节点最后一位插入新节点,node为新节点的名称。
let newnode = document.createElement("p");
newnode.innerHTML = "新节点";
box.appendChild(newnode);
console.log(boxChild);

removeChild方法
removeChild(node):删除指定父级元素的某个子节点。
项目目标:点击删除按钮,依次删除列表中书籍。

btn.onclick = function(){
list.removeChild(list.childNodes[1]);
}
parentNode属性
parentNode属性:返回指定节点的父节点。
<div id="box">
<p id="box-item1">第一个child节点</p>
<h4>第二个child节点</h4>
<div>第三个child节点</div>
</div>
<script>
let box_item1 = document.getElementById("box-item1");
console.log(box_item1.parentNode);
</script>

项目目标:点击叉号删除内容。

x.onclick = function(){
document.body.removeChild(this.parentNode);
}
replaceChild方法
replaceChild(newnode,oldnode)方法:用新节点替换之前的节点。
<div id="box">
<p id="box-item1">第一个child节点</p>
<h4>第二个child节点</h4>
<div id="box-item3">第三个child节点</div>
</div>
<script>
let box_item1 = document.getElementById("box-item1");
console.log(box_item1.parentNode);
let h1 = document.createElement("h1");
h1.innerHTML = "新节点 第三个child节点";
let box_item3 = document.getElementById("box-item3");
let box = document.getElementById("box");
box.replaceChild(h1, box_item3);
</script>

insertBefore方法
insertBefore可以在已有的子节点前插入一个新的子节点。项目目标:点击按钮,在ul标记子节点的第一位插入包含内容“我的世界”,文字颜色为红色的h4节点。

let btn = document.getElementById("button");
let game = document.getElementById("game");
btn.onclick = function() {
let newGame = document.createElement("h4");
newGame.innerHTML = "我的世界";
newGame.style.color = "red";
newGame.style.paddingLeft = "40px";
game.insertBefore(newGame, game.firstChild);
}
setAttribute属性
setAttribute属性:添加指定的属性,并为其赋指定的值。
项目目标:点击“变”按钮,将输入框变为按钮。

let btn = document.getElementById("btn");
let input = document.getElementById("put");
btn.onclick = function() {
input.setAttribute("type", "button");
}