新聞中心
什么是DOM樹?
DOM(Document Object Model)即文檔對象模型。通過DOM樹這樣一種結構,不?僅可以直觀的看到HTML的整體結構,還可以利用DOM樹的一些屬性獲取到某個元素的子節(jié)點和節(jié)點名稱等信息。

安丘網(wǎng)站建設公司成都創(chuàng)新互聯(lián),安丘網(wǎng)站設計制作,有大型網(wǎng)站制作公司豐富經(jīng)驗。已為安丘成百上千家提供企業(yè)網(wǎng)站建設服務。企業(yè)網(wǎng)站搭建\外貿(mào)網(wǎng)站建設要多少錢,請找那個售后服務好的安丘做網(wǎng)站的公司定做!
HTML文檔結構:
樹形結構:
childNodes和nodeName屬性
childNodes屬性:獲取當前節(jié)點的子節(jié)點。
第一個child節(jié)點
第二個child節(jié)點
第三個child節(jié)點
空格和換行也屬于一個節(jié)點,用text表示。
for(let i = 1; i < boxChild.length; i += 2)
console.log(boxChild[i]);
獲取1、3、5……奇數(shù)節(jié)點。
nodeName屬性:返回節(jié)點名稱。
for(let i = 1; i < boxChild.length; i += 2)
console.log(boxChild[i].nodeName);
appendChild方法
appendChild(node):在子節(jié)點最后一位插入新節(jié)點,node為新節(jié)點的名稱。
let newnode = document.createElement("p");
newnode.innerHTML = "新節(jié)點";
box.appendChild(newnode);
console.log(boxChild);removeChild方法
removeChild(node):刪除指定父級元素的某個子節(jié)點。
項目目標:點擊刪除按鈕,依次刪除列表中書籍。
btn.onclick = function(){
list.removeChild(list.childNodes[1]);
}parentNode屬性
parentNode屬性:返回指定節(jié)點的父節(jié)點。
第一個child節(jié)點
第二個child節(jié)點
第三個child節(jié)點
項目目標:點擊叉號刪除內(nèi)容。
x.onclick = function(){
document.body.removeChild(this.parentNode);
}replaceChild方法
replaceChild(newnode,oldnode)方法:用新節(jié)點替換之前的節(jié)點。
第一個child節(jié)點
第二個child節(jié)點
第三個child節(jié)點
insertBefore方法
insertBefore可以在已有的子節(jié)點前插入一個新的子節(jié)點。項目目標:點擊按鈕,在ul標記子節(jié)點的第一位插入包含內(nèi)容“我的世界”,文字顏色為紅色的h4節(jié)點。
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屬性:添加指定的屬性,并為其賦指定的值。
項目目標:點擊“變”按鈕,將輸入框變?yōu)榘粹o。
let btn = document.getElementById("btn");
let input = document.getElementById("put");
btn.onclick = function() {
input.setAttribute("type", "button");
} 當前題目:一文詳解Javascript DOM樹結構
本文地址:http://www.dlmjj.cn/article/ccojsed.html


咨詢
建站咨詢
