DOM HTMLCollection
JavaScript基础 2022-05-13 16:49:0722小码哥的IT人生shichen
DOM HTMLCollection
HTMLCollection 对象
HTMLCollection 对象是 HTML 元素的类似数组的列表。
诸如 getElementsByTagName()
之类的方法会返回 HTMLCollection。
属性和方法
可以在 HTMLCollection 对象上使用以下属性和方法:
属性 / 方法 | 描述 |
---|---|
item() | 返回 HTMLCollection 中指定索引处的元素。 |
length | 返回 HTMLCollection 中的元素数。 |
namedItem() | 返回 HTMLCollection 中有指定 ID 或名称的元素。 |
实例
示例代码:
获取 HTMLCollection:
var x = document.getElementsByTagName("P"); // 返回文档中所有 P 元素的集合
完整实例:
<!DOCTYPE html> <html> <body> <h1>HTMLCollection 对象</h1> <p>使用 getElementsByTagName() 方法来返回 HTMLCollection:</p> <script> var x = document.getElementsByTagName("P"); document.write(x); </script> </body> </html>
可以使用本站在线JavaScript测试工具测试上述代码运行效果:http://www.phpcodeweb.com/runjs.html
示例代码:
输出文档中 <p>
元素的数量:
var x = document.getElementsByTagName("P"); document.write(x.length);
完整实例:
<!DOCTYPE html> <html> <body> <h1>HTMLCollection 对象</h1> <p>使用 getElementsByTagName() 方法来返回 HTMLCollection。</p> <p>此页面上 P 元素的数量:</p> <script> var x = document.getElementsByTagName("P"); document.write(x.length); </script> </body> </html>
可以使用本站在线JavaScript测试工具测试上述代码运行效果:http://www.phpcodeweb.com/runjs.html
示例代码:
循环遍历 HTMLCollection 中的每个元素:
x = document.getElementsByTagName("*"); l = x.length; for (i = 0; i < l; i++) { document.write(x[i].tagName + "<br>"); }
完整实例:
<!DOCTYPE html> <html> <body> <h1>HTMLCollection 对象</h1> <p>循环遍历此页面上的每个 HTML 元素,并输出其标记名称:</p> <script> var x, i, l; x = document.getElementsByTagName("*"); l = x.length; for (i = 0; i < l; i++) { document.write(x[i].tagName + "<br>"); } </script> </body> </html>
可以使用本站在线JavaScript测试工具测试上述代码运行效果:http://www.phpcodeweb.com/runjs.html