How to get all ID of the DOM elements with JavaScript ?

Given a HTML document and the task is to get the all ID of the DOM elements in an array. There are two methods to solve this problem which are discusses below:Â
Approach 1:
- First select all elements using $(‘*’) selector, which selects every element of the document.
- Use .each() method to traverse all elements and check if it has an ID.
- If it has an ID then push it into the array.
Example: This example implements the above approach.Â
html
<!DOCTYPE html><html lang="en">Â
<head>    <title>        How to get all ID of the DOM        elements with JavaScript ?    </title>Â
    <script src=    </script></head>Â
<body>    <h1 style="color: green">        zambiatek    </h1>Â
    <p>        Click on the button to get         all IDs in an array.    </p>Â
    <button onclick="muFunc()">        Click Here    </button>Â
    <p id="GFG"></p>Â
    <script>        let res = document.getElementById("GFG");Â
        function muFunc() {            let ID = [];                         $("*").each(function () {                if (this.id) {                    ID.push(this.id);                }            });Â
            res.innerHTML = ID;        }    </script></body>Â
</html> |
Output:
Approach 2:
- First select all elements using $(‘*’) selector, Which selects every element of the Document.
- Use .map() method to traverse all element and check if it has ID.
- If it has ID then push it in the array using .get() method.
Example: This example implements the above approach.Â
html
<!DOCTYPE html><html lang="en">Â
<head>    <title>        How to get all ID of the DOM        elements with JavaScript ?    </title>Â
    <script src=    </script></head>Â
<body>    <h1 style="color: green">        zambiatek    </h1>Â
    <p>        Click on the button to get         all IDs in an array.    </p>Â
    <button id="Geeks" onclick="muFunc()">        Click Here    </button>Â
    <p id="GFG"></p>Â
    <script>        let res = document.getElementById("GFG");                 function muFunc() {            let ID = [];                         ID = $("*").map(function() {                if (this.id) {                    return this.id;                }            }).get();            res.innerHTML = ID;        }    </script></body>Â
</html> |
Output:




