標籤:rip 一個 簽名 element i++ 等價 引號 擷取 調用
有3種DOM方法可擷取元素節點,分別通過ID、標籤名、類名來擷取。
1.getElementsById
通過id來訪問元素,注意開頭字母不是寫成大寫,如果把它寫錯成“GetElementById”,是無效的。
document.getElementsById( id ) 這個id值必須寫在單引號或者雙引號裡面
2.getElementsByTagName
getElementsByTagName 通過標籤名來訪問元素,方法返回一個對象數組,每個對象分別對應著文檔裡有著給定標籤的一個元素。
document.getElementsByTagName( Tag )
3.getElementsByClassName
getElementsByClassName 通過類名來訪問元素,與TagName類似,都是返回一個數組,它還可以尋找帶有多個類名的元素。
getElementsByClassName( class )
注意是訪問帶有多個類名的元素,不是可以訪問多個類名。
1 document.getElementsByClassName("a b");2 //只能訪問3 <div class="a b"></div>4 //不可訪問5 <div class="a"></div>6 <div class="b"></div>
擷取和設定屬性
1.getAttribute
這個方法用來擷取節點的各個屬性值,但不屬於 document 對象,所以不能通過document 對象調用。
1 //用法 2 <p title="hello">Yes!</p> 3 <p>Yes!</p> 4 var paras = document.getElementsByTagName("p"); 5 for ( var i = 0; i < paras.length; i++ ){ 6 title_text = paras[ i ].getAttribute("title"); 7 if ( title_text != null){//等價( title_text ) 8 alert( title_text ); 9 } 10 }
2.setAttribute
setAttribute()用來設定節點的各個屬性值。
1 //用法 2 <p title="hello">Yes!</p> 3 var paras = document.getElementsByTagName("p"); 4 for ( var i = 0; i < paras.length; i++ ){ 5 var title_text = paras[ i ].getAttribute("title"); 6 if ( title_text ){ 7 paras[ i ].setAttribute("title","hey"); 8 alert( paras[ i ].getAttribute("title") ); 9 }10 }
這5個方法是編寫許多DOM 指令碼的基礎!
Javascript·擷取元素、設定屬性