HTML - DOM HTMLCollection length 属性



HTML DOM HTMLCollection 的 **length** 属性返回 HTMLCollection 中元素的数量。这是一个只读属性,也是一个非常有用的属性,因为它在使用循环时可以作为迭代器。

语法

HTMLCollection.length;

返回值

它返回一个数字,表示 HTMLCollection 中元素的数量。

HTML DOM HTMLCollection 'length' 属性示例

以下是一些说明 length 属性用法的示例。

统计元素数量

以下示例返回文档中存在的 'h1' 元素的数量。

<!DOCTYPE html>
<html lang="en">
<head>
    <title>DOM HTMLCollection length Property</title>
</head>
<body>
    <h1>This is a learning domain</h1>
    <h1>Welcome to Tutorials Point</h1>
    <h1>Welcome to Tutorix</h1>
    <p>Click below to get the number of 'h1' elements</p>
    <button onclick="fun()">Click me</button>
    <p id="type"></p>
    <script>
        function fun() {
            let x = document.getElementsByTagName("h1").length;
            document.getElementById("type").innerHTML =
                "Number of 'h1' elements :" + x;
        }
    </script>
</body>
</html>

更改背景颜色

在以下示例中,length 属性用作迭代器来更改类名为 'change' 的元素的背景颜色。

<!DOCTYPE html>
<html lang="en">
<head>
    <title>DOM HTMLCollection length Property</title>
</head>
<body>
    <p>Click below to change background color of p element with class name = change</p>
    <button onclick="fun()">Click me</button>
    <P class="change">This is a learning domain</p>
    <p>Welcome to Tutorials Point</p>
    <p class="change">Welcome to Tutorix</p>
    <p id="type"></p>
    <script>
        function fun() {
            let x = document.getElementsByClassName("change");
            for (let i = 0; i < x.length; i++) {
                x[i].style.backgroundColor = "#04af2f";
            }
        }
    </script>
</body>
</html>

支持的浏览器

属性 Chrome Edge Firefox Safari Opera
length 是 1 是 12 是 1 是 1 是 12.1
html_dom_htmlcollection_reference.htm
广告
© . All rights reserved.