介紹幾個js DOM的常用方法 獲取元素節點 getElementById getElementsByTagName getElementsByClassName 先寫一個簡單的網頁做測試: 1. getElementById 1.先定義變數 var contentId = document.get ...
介紹幾個js DOM的常用方法
獲取元素節點 getElementById getElementsByTagName getElementsByClassName
先寫一個簡單的網頁做測試:
/*
test.html
*/
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>test</title> </head> <body> <p id="contentId" style="width:500px; height: 30px;background-color: #ccc">這段的id是contentId。</p> <p class="contentClass" style="width:500px; height: 30px;background-color: #ccc">這段的class name是contentClass。</p> </body> </html>
1. getElementById
1.先定義變數 var contentId = document.getElementById("contentId");
2.然後輸出對象 contentId 就返回id為 contentId 的元素對象( <p id="contentId" style="width:500px; height: 30px;background-color: #ccc"> )。見下圖:
2. getElementsByTagName
1.還是先定義變數 var contentTag = document.getElementsByTagName("p");
2.接著我輸出 contentTag ,它返回 HTMLCollection [ <p#contentId>, <p.contentClass> ] 共兩個,一個以#開頭表示id,另一個以.開頭表示Class name。
3.繼續 contentTag[0] 輸出 <p id="contentId" style="width:500px; height: 30px;background-color: #ccc">
contentTag[1] 輸出 <p class="contentClass" style="width:500px; height: 30px;background-color: #ccc">
由此可知 getElementsByTagName 返回的是數組!
3. getElementsByClassName
1. var contentClass = document.getElementsByClassName("contentClass");
2. contentClass 輸出 HTMLCollection [ <p.contentClass> ] 返回一個元素對象數組,即使只有一個。
3. contentClass[0] 輸出 <p class="contentClass" style="width:500px; height: 30px;background-color: #ccc">
我們常用的還有 getAttribute,setAttribute,ChildNodes, nodeType, nodeValue, firstChild, lastChild 方法獲取一些信息。
4.分別用 getAttribute 和 setAttribute 獲取和設置屬性:
改變style屬性後:
5.那麼這是childNOdes:
也就是說, <p></p> 在遇到塊元素時,塊元素之間會有一個換行符 <br> ,瀏覽器在查找子節點時會將它視為一個文本節點。從圖中也可以看出 childNodes 返回的也是數組。
那如果是<p#contentId>呢?
nodeType 的值有12種,常用的也就三種:1表示元素節點,2表示屬性節點,3表示文本節點。
nodeValue 不僅可以獲取文本節點的值,還可以改變文本節點的值。
js的dom方法還有好多,可以看看這個W3school JS參考手冊,相信對初學者有很大幫助。
XD!