DOM(Document Object Model)即文檔對象模型。通過DOM樹這樣一種結構,不僅可以直觀的看到HTML的整體結構,還可以利用DOM樹的一些屬性獲取到某個元素的子節點和節點名稱等信息。
HTML文檔結構:
樹形結構:
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(node):在子節點最后一位插入新節點,node為新節點的名稱。
let newnode=document.createElement("p");
newnode.innerHTML="新節點";
box.appendChild(newnode);
console.log(boxChild);
removeChild(node):刪除指定父級元素的某個子節點。
項目目標:點擊刪除按鈕,依次刪除列表中書籍。
btn.onclick=function(){
list.removeChild(list.childNodes[1]);
}
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(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可以在已有的子節點前插入一個新的子節點。
項目目標:點擊按鈕,在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屬性:添加指定的屬性,并為其賦指定的值。
項目目標:點擊“變”按鈕,將輸入框變為按鈕。
let btn=document.getElementById("btn");
let input=document.getElementById("put");
btn.onclick=function() {
input.setAttribute("type", "button");
}
.什么是Dom樹
Dom樹簡單來說就是瀏覽器解析從服務器接收的html代碼轉化為樹形結構,使之每一項都成為一個Dom對象
2.Dom樹的組成及關系
Dom樹是由html代碼中的每一個標簽,屬性等對象轉化的節點組成,html為根節點其他的為子節點,節點中的各種關系可以用我們的家族關系來描述,主要是父與子,兄與弟的關系
3.Dom樹的作用
1.便于瀏覽器通過Dom樹結構渲染整個網頁頁面(與CSS共同作用)
2.便于用戶通過Dom樹對其節點的增刪改查操作
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Dom樹</title>
</head>
<body>
<ul>
<li>鄭州</li>
<li>開封</li>
<li>洛陽</li>
</ul>
</body>
</html>
由上面的html代碼可以轉化的Dom樹結構如下圖所示
Dom樹結構
由上圖可知此Dom樹中根元素HTML有兩個子元素:head與body;head與body是HTML的子元素,所以它們是父子關系;head與body在Dom節點中是兄弟關系;body節點中的ul與li之間是父子關系,li之間是兄弟關系
4.Dom樹節點間的層次關系
深度:是相對于根節點而言,如果深度相同并且父節點也相同,則可認為兩個節點是兄弟節點
索引:是相對于父節點而言,索引相同的節點并不一定是兄弟節點,因為其父節點不一定相同
Dom樹節點的層次
*請認真填寫需求信息,我們會在24小時內與您取得聯系。