HTML - DOM NodeList keys() Method



HTML DOM NodeList keys() method used to get an iterator which allows us to go through all the keys contained in the nodelist. These keys are unsigned integer.

Syntax

nodelist.keys();

Parameter

This method does not accept any parameter.

Return value

It returns an iterator.

Example of HTML DOM Nodelist 'keys()' Method

The following examples illustrates implementation of keys() method to get child nodes and their keys.

Get the Child Nodes

In the following example we have created several elements and then appended them to one node that is parent node and then with keys() method, we get an iterator to get all keys from nodelist.

<!DOCTYPE html>
<html lang="en">
<head>
    <title>HTML DOM Nodelist keys() 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("table");
            nodes.appendChild(nodeOne);
            nodes.appendChild(nodeTwo);
            nodes.appendChild(nodeThree);
            nodes.appendChild(nodeFour);
            let elelist = nodes.childNodes;
            for (let i of elelist.keys()) {
                x.innerHTML += elelist[i].localName + "<br>";
            }
        };
    </script>
</body>
</html>

Get keys of Child Nodes

The following example returns all the keys of the child nodes.

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

Supported Browsers

Method Chrome Edge Firefox Safari Opera
keys() Yes 51 Yes 16 Yes 50 Yes 10 Yes 38
html_dom.htm
Advertisements