DOM獲取元素節點主要通過三種方式(想象樹形結構):
- 通過標籤id獲取
- 通過標籤class獲取
- 通過標籤名獲取
下面準備演示示例:
<body>
<ul>
<li>111</li>
<li class = 'box'>111</li>
<li class = 'hello'>111</li>
<li class = 'box'>111</li>
<li>111</li>
</ul>
<input type = "text" name = 'hello'/>
<span name = 'hello'></span>
<ol id = 'ol1'>
<li>222</li>
<li class = 'box'>222</li>
<li class = 'box'>222</li>
</ol>
</body>
一、通過id獲取(寫在上節裏)
document.getElementById(id) (沒有node節點方法,因爲id唯一)
功能:通過id名獲取符合條件的元素節點
二、通過標籤名獲取
document.getElementByTagName(標籤名) //獲取整個HTML頁面中的標籤
node.getElementsByTagName(標籤名) //獲取node節點子樹上的標籤
返回值:一個集合(用法和集合差不多)
功能:通過標籤名獲取符合條件的元素節點
//case1 :獲取頁面中所有的<li>標籤
window.onload = function(){
var aLis = document.getElementsByTagName("li");
alert(aLis);
//collection使用起來和數組一樣
alert(aLis.length); //8
}
輸出結果:object HTML collection(HTML對象集合),使用起來和數組一樣
//case2 : 獲取<ol>標籤內的<li>標籤
window.onload = function(){
var ol = document.getElementById("ol1");
var aLis = ol.getElementsByTagName("li");
//獲取ol下的li節點
alert(aLis.length);
}
三、通過ClassName獲取節點
document.getElementsByClassName(classname)
node.getElementsByClassName(classname)
功能:通過Class名獲取符合條件的元素節點
//通過classname獲取當前頁面所有的classname爲box的標籤
window.onload = function(){
var nodes = document.getElementsByClassName("box");
//循環遍歷獲取到的,classname爲box的集合
for(var i = 0;i < nodes.length; i++){
//將集合中的標籤的背景色設置爲red
nodes[i].style.backgroundColor = "red";
}
}
同上面一樣,也可以獲取部分子樹標籤
//獲取id爲ol1下的classname爲box的標籤
window.onload = function(){
var ol = document.getElementById("ol1");
var nodes = ol.getElementsByClassName("box");
for(var i = 0;i < nodes.length; i++){
//將集合中的標籤的背景色設置爲red
nodes[i].style.backgroundColor = "red";
}
}