2 DOM
2.1 DOM介紹
◆ “W3C 文檔對象模型 (DOM) 是中立于平臺和語言的接口,
它允許程序和腳本動態(tài)地訪問和更新文檔的內容、樣式和結構?!?◆ HTML DOM 是關于如何增,刪,改,查 HTML 元素的標準。
◆ HTML DOM 將 HTML 文檔視作樹結構。這種結構被稱為節(jié)點樹:

image.png
2.2 節(jié)點
◆ 節(jié)點樹就是由一個個節(jié)點組成
◆ 父(parent)、子(child)和同胞(sibling)等術語用于描述這些關系。
◆ 父節(jié)點擁有子節(jié)點。同級的子節(jié)點被稱為同胞(兄弟或姐妹)。
nextElementSibling; // 下一個兄弟元素
previousElementSibling; // 上一個兄弟元素

image.png
2.3 如何獲取節(jié)點(查詢)
◆ getElementById()
// 使用id名獲得元素
◆ getElementsByTagName()
// 使用標簽名獲得數(shù)組,用數(shù)組[0] 得到元素
◆ getElementsByClassName()
// 使用類名獲得數(shù)組,用數(shù)組[0] 得到元素
◆ querySelectorAll("div>.yxh"); // 得到div下所有.yxh 的元素.
◆ querySelector("div>.yxh"); // 得到div下第一個.yxh元素.
// querySelector返回滿足條件的第一個元素(node),而querySelectorAll返回滿足條件的所有元素(nodelist);
在都沒有滿足條件的元素情況下:querySelector返回__Null__,而querySelectorAll返回空的數(shù)組__[]__;
2.4 節(jié)點的分類nodeType
◆ nodeType==1 為元素節(jié)點
◆ nodeType==2 為屬性節(jié)點
◆ nodeType==3 位文本節(jié)點 // 換行也是文本節(jié)點
◆ nodeName // 返回節(jié)點的名字
◆ nodeValue // 返回節(jié)點的值
Object.nodetype // 使用方法
2.5 增加獲取節(jié)點
◆ 創(chuàng)造插入節(jié)點
createElement() ; // 創(chuàng)建元素節(jié)點
createTextNode(); // 創(chuàng)建文本節(jié)點
appendChild(); // 將新元素作為父元素的最后一個子元素進行添加。
insertBefore(newNote,childElementNode); // 插入新元素
◆ Attribute 屬性節(jié)點
getAttributeNode(att); // 獲得屬性節(jié)點 方法 1
attributes["title"]; // 獲得屬性節(jié)點 方法 2
createAttribute(); // 創(chuàng)建屬性
setAttributeNode(att); // 設置屬性節(jié)點
◆ example :
var p=document.createElement("p"); // 創(chuàng)建元素節(jié)點
var txt = document.createTextNode("hello world"); // 創(chuàng)建文本節(jié)點
var att = document.createAttribute("title"); // 創(chuàng)建屬性 title
att.value = "我是新增加的屬性節(jié)點" // 設置 title 屬性值
p.appendChild(txt); // 增加子節(jié)點
p.setAttributeNode(att); // 設置屬性節(jié)點
document.body.appendChild(p); // 增加子節(jié)點
◆ parentNode.insertBefore(newNode,childElementNode)
// 新元素可以插入想要的位置.
2.6 刪除節(jié)點
◆ parentNode.remove(); // 刪除父節(jié)點
◆ parentNode.removeChild(childNode); // 刪除子節(jié)點
2.7 修改元素節(jié)點的內容
◆ innerHTML // 設置或返回表格行的開始和結束標簽之間的 HTML。(文本以及標簽)
◆ object.style.color=”pink” // 修改css樣式
◆ object.style.cssText ="width:200px;height:200px;background-color:red" // 修改css樣式
2.8 修改節(jié)點(替換節(jié)點)
◆ parentNode.replaceChild(newNode,oldNode);
example:
var newElement = document.createElement("img"); // 創(chuàng)建新的img元素
newElement.style.cssText="width:100px;height:100px;background-color:gold"; // 設置新元素img的樣式
newElement.src="images/logo.gif"; // 加載新元素img的圖片
box.replaceChild(newElement,p); // 替換原來的 p 元素
2.9 事件(event)
JavaScript與HTML之間的交互式通過事件實現(xiàn)的
onclick // 點擊事件
onfocus // 獲得焦點事件
onblur // 元素數(shù)去焦點
onmouseover // 鼠標移到某元素之上
onmouseout // 鼠標從某元素移開
// 有事件一定有對應一個處理結果,用函數(shù)表示
box.onclick=function(){
.......................syntax
.......................syntax
};

image.png