HTML - DOM NodeList 的 forEach() 方法



HTML DOM nodelist 的 **forEach()** 方法會按照列表中插入順序對列表中的每個值對呼叫引數中提到的回撥函式一次。

語法

nodelist.forEach(callback(currentValue, currentIndex, listObj), thisArg);

引數

它接受五個引數,其中兩個是必需引數,三個是可選引數。

引數 描述
callback 這是必需引數。它表示要對 nodelist 的每個元素執行的函式。它接受三個引數。
currentValue 這是必需引數。它表示 nodelist 中的當前節點。
currentIndex 這是一個可選引數。它表示 currentValue 在 nodelist 中的索引。
listObj 這是一個可選引數。它表示正在應用 forEach() 方法的 nodelist。
thisArg 這是一個可選引數。它表示在執行回撥函式時用作 this 的值。

返回值

它不返回任何值。

HTML DOM NodeList 'forEach()' 方法示例

以下示例說明了 **forEach()** 方法的實現。

獲取所有子節點

以下示例返回父節點的所有子節點。

<!DOCTYPE html>
<html lang="en">
<head>
    <title>HTML DOM Nodelist forEach() Method</title>
</head>
<body>
    <p>Click to get the child nodes:</p>
    <button onclick="fun()">Click me</button>
    <p id="entry"></p>
    <script>
        function fun() {
            let x = document.getElementById("entry");
            let nodes = document.createElement("section");
            let nodeOne = document.createElement("h1");
            let nodeTwo = document.createElement("p");
            let nodeThree = document.createElement("h2");
            let nodeFour = document.createElement("span");
            nodes.appendChild(nodeOne);
            nodes.appendChild(nodeTwo);
            nodes.appendChild(nodeThree);
            nodes.appendChild(nodeFour);
            let elelist = nodes.childNodes;
            elelist.forEach(
                function (currentValue, currentIndex, listObj) {
                    x.innerHTML += currentValue.localName + "<br>";
                });
        }
    </script>
</body>
</html>

獲取 body 標籤的子節點

以下示例返回 <body> 元素的所有子節點。

<!DOCTYPE html>
<html>
<head>
    <title>HTML DOM Nodelist forEach() Method</title>
</head>
<body>
    <p>I am para 1</p>
    <p>I am para 2</p>
    <h1>random text</h1>
    <p id="forEach"></p>
    <script>
        let x = document.body.childNodes;
        let text = "";
        x.forEach(
            function (currentValue, currentIndex) {
                text += currentIndex + " " + currentValue + "<br>";
            });
        document.getElementById("forEach").innerHTML = text;
    </script>
</body>
</html>

支援的瀏覽器

方法 Chrome Edge Firefox Safari Opera
forEach() 支援 51 支援 16 支援 50 支援 10 支援 38
廣告