Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

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

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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




<head>
    <script src=
    </script>
</head>
<body>
    <h1 style="color: green">
        GeeksforGeeks
    </h1>
      
    <p id="GFG_UP"></p>
      
    <button onclick="gfg_Run()">
        Click Here
    </button>
      
    <p id="GFG_DOWN"></p>
      
    <script>
        var el_up = document.getElementById("GFG_UP");
        var el_down = document.getElementById("GFG_DOWN");
        el_up.innerHTML = "Click on the button to get "
                            + "all IDs in an array.";
          
        function gfg_Run() {
            var ID = [];
            $("*").each(function() {
                if (this.id) {
                    ID.push(this.id);
                }
            });
            el_down.innerHTML = ID;
        }
    </script>
</body>

Output:

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

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

Approach 2:

Example 2: This example implements the above approach. 

html




<head>
   <script src=
    </script>
</head>
<body>
    <h1 style="color: green">
        GeeksforGeeks
    </h1>
      
    <p id="GFG_UP"></p>
      
    <button onclick="gfg_Run()">
        Click Here
    </button>
      
    <p id="GFG_DOWN"></p>
      
    <script>
        var el_up = document.getElementById("GFG_UP");
        var el_down = document.getElementById("GFG_DOWN");
        el_up.innerHTML = "Click on the button to "
                    + "get all IDs in an array.";
          
        function gfg_Run() {
            var ID = [];
              
            ID = $("*").map(function() {
                if (this.id) {
                    return this.id;
                }
            }).get();
            el_down.innerHTML = ID;
        }
    </script>
</body>

Output:

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

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


My Personal Notes arrow_drop_up
Last Updated : 24 Jan, 2023
Like Article
Save Article
Similar Reads
Related Tutorials