JavaScript HTML DOM 集合
Ang HTMLCollection object
getElementsByTagName()
Ang paraan ay nagbibigay ng HTMLCollection Objekto.
Ang HTMLCollection ay isang listahan ng HTML elementong katulad ng array (koleksyon).
Ang sumusunod na code ay pinapili ang lahat ng <p> elemento sa dokumento:
实例
var x = document.getElementsByTagName("p");
Ang mga elemento sa koleksyon ay ma-access sa pamamagitan ng index number.
Kung nais mong ma-access sa ikalawang <p> elemento, maaari mong gumawa ng ganito:
y = x[1];
Komentaryo:Ang index ay nagsisimula sa 0.
Panlalim ng HTML HTMLCollection
length
Ating nagtataglay ang atributo ng bilang ng mga elemento sa HTMLCollection:
实例
var myCollection = document.getElementsByTagName("p"); document.getElementById("demo").innerHTML = myCollection.length;
实例解释:
- 创建所有 <p> 元素的集合
- 显示集合的长度
length
属性在您需要遍历集合中元素时是有用的:
实例
改变所有 <p> 元素的背景色:
var myCollection = document.getElementsByTagName("p"); var i; for (i = 0; i < myCollection.length; i++) { myCollection[i].style.backgroundColor = "red"; }
HTMLCollection 并非数组!
HTMLCollection 也许看起来像数组,但并非数组。
您能够遍历列表并通过数字引用元素(就像数组那样)。
不过,您无法对 HTMLCollection 使用数组方法,比如 valueOf()
、pop()
、push()
或 join()
。