Friday, July 3, 2026
HomeLanguagesJavascriptHow to get all ID of the DOM elements with JavaScript ?

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">
        neveropen
    </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:

id-attr

Approach 2:

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">
        neveropen
    </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:

id-attr2

RELATED ARTICLES

3 COMMENTS

Most Popular

Dominic
32519 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6900 POSTS0 COMMENTS
Nicole Veronica
12015 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12110 POSTS0 COMMENTS
Shaida Kate Naidoo
7019 POSTS0 COMMENTS
Ted Musemwa
7262 POSTS0 COMMENTS
Thapelo Manthata
6976 POSTS0 COMMENTS
Umr Jansen
6967 POSTS0 COMMENTS