HTML - DOM NodeList length 屬性



HTML DOM Nodelist 的 **length** 屬性是一個只讀屬性,它返回節點列表中的專案數。

語法

nodelist.length;

返回值

它返回一個整數,表示節點列表中的專案數。

HTML DOM Nodelist 'length' 屬性的示例

以下是一些說明 length 屬性用法的示例。

計算 body 中子元素的數量

以下示例返回 <body> 中子元素的數量。

<!DOCTYPE html>
<html lang="en">
<head>
    <title>HTML DOM Nodelist 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 'body' elements</p>
    <button onclick="fun()">Click me</button>
    <p id="type"></p>
    <script>
        function fun() {
            let x = document.body.childNodes.length;
            document.getElementById("type").innerHTML =
                "Number of 'body' elements :" + x;
        }
    </script>
</body>
</html>

計算 Section 元素的子元素數量

以下示例返回 <section> 中子元素的數量。

<!DOCTYPE html>
<html lang="en">
<head>
    <title>HTML DOM Nodelist length Property</title>
</head>
<body>
    <section id="sec">
        <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 elements in
        <section>
            </p>
        </section>
        <button onclick="fun()">Click me</button>
        <p id="type"></p>
        <script>
            function fun() {
                let x = document.getElementById("sec").childNodes.length;
                document.getElementById("type").innerHTML = "Number of elements in section :" + x;
            }
        </script>
</body>
</html>

計算 h1 元素的數量

以下示例返回文件中使用的 h1 元素的數量。

<!DOCTYPE html>
<html lang="en">
<head>
    <title>HTML DOM Nodelist 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 屬性迴圈遍歷節點以更改所需元素的樣式。

<!DOCTYPE html>
<html lang="en">
<head>
    <title>HTML DOM Nodelist 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
廣告