JavaScript - 2.Dom<增刪改查> + 事件

2 DOM

2.1 DOM介紹

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

2.2 節點

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

2.3 如何獲取節點(查詢)

◆ getElementById()   
 // 使用id名獲得元素

◆ getElementsByTagName() 
// 使用標簽名獲得數組,用數組[0] 得到元素

◆ getElementsByClassName()
 // 使用類名獲得數組,用數組[0] 得到元素

◆ querySelectorAll("div>.yxh"); // 得到div下所有.yxh 的元素.
◆ querySelector("div>.yxh");  // 得到div下第一個.yxh元素.

// querySelector返回滿足條件的第一個元素(node),而querySelectorAll返回滿足條件的所有元素(nodelist);
在都沒有滿足條件的元素情況下:querySelector返回__Null__,而querySelectorAll返回空的數組__[]__;

2.4 節點的分類nodeType

◆ nodeType==1  為元素節點
◆ nodeType==2  為屬性節點
◆ nodeType==3  位文本節點  // 換行也是文本節點
◆ nodeName // 返回節點的名字
◆ nodeValue // 返回節點的值
Object.nodetype // 使用方法

2.5 增加獲取節點

◆ 創造插入節點
createElement() ; // 創建元素節點
createTextNode(); // 創建文本節點
appendChild(); // 將新元素作為父元素的最后一個子元素進行添加。
insertBefore(newNote,childElementNode); // 插入新元素

◆ Attribute 屬性節點
getAttributeNode(att); // 獲得屬性節點 方法 1
attributes["title"]; // 獲得屬性節點 方法 2
createAttribute(); // 創建屬性
setAttributeNode(att); // 設置屬性節點

◆ example :
var p=document.createElement("p"); // 創建元素節點
var txt = document.createTextNode("hello world"); // 創建文本節點
var att = document.createAttribute("title");  // 創建屬性 title
att.value = "我是新增加的屬性節點"  // 設置 title 屬性值
p.appendChild(txt); // 增加子節點
p.setAttributeNode(att); // 設置屬性節點
document.body.appendChild(p);  // 增加子節點

◆ parentNode.insertBefore(newNode,childElementNode) 
// 新元素可以插入想要的位置.

2.6 刪除節點

◆ parentNode.remove(); // 刪除父節點
◆ parentNode.removeChild(childNode); // 刪除子節點

2.7 修改元素節點的內容

◆ innerHTML // 設置或返回表格行的開始和結束標簽之間的 HTML。(文本以及標簽)
◆ object.style.color=”pink” // 修改css樣式
◆ object.style.cssText ="width:200px;height:200px;background-color:red" // 修改css樣式

2.8 修改節點(替換節點)

◆ parentNode.replaceChild(newNode,oldNode);

example:
var newElement = document.createElement("img");   // 創建新的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之間的交互式通過事件實現的
onclick // 點擊事件
onfocus // 獲得焦點事件
onblur // 元素數去焦點
onmouseover  // 鼠標移到某元素之上
onmouseout  // 鼠標從某元素移開

// 有事件一定有對應一個處理結果,用函數表示
    box.onclick=function(){
        .......................syntax
        .......................syntax
    };
image.png
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容