Thursday, May 7, 2026
HomeLanguagesJavascriptHow to dynamically insert id into table element using JavaScript ?

How to dynamically insert id into table element using JavaScript ?

This article explains how to dynamically insert “id” into the table element. This can be done by simply looping over the tables and add “id”s dynamically.

Syntax:

  • The setAttribute() method adds the specified attribute to an element and gives the specified value.
    table.setAttribute("id", "Dynamically Generated ID")
  • It can also be done by accessing the “id” of the selected element (table).
    table.id = "Dynamically Generated ID";

Example:

HTML




<!DOCTYPE html>
<html>
 
<head>
    <style>
        table,
        th,
        td {
            border: 1px solid black;
            border-collapse: collapse;
            margin: auto;
            width: 50%;
            text-align: center;
        }
    </style>
</head>
 
<body>
    <h1 style="color:green;text-align: center;">
        GeeksForGeeks
    </h1>
     
    <table>
        <tr>
            <th>Firstname</th>
            <th>Lastname</th>
        </tr>
        <tr>
            <td>Jill</td>
            <td>Smith</td>
        </tr>
        <tr>
            <td>Eve</td>
            <td>Jackson</td>
        </tr>
    </table>
    <br>
 
    <table>
        <tr>
            <th>Firstname</th>
            <th>Lastname</th>
        </tr>
        <tr>
            <td>John</td>
            <td>Doe</td>
        </tr>
        <tr>
            <td>Emma</td>
            <td>Allen</td>
        </tr>
    </table>
 
    <script>
        // Getting the table element
        var tables = document
            .getElementsByTagName("table");
 
        // Looping over tables
        for (var i = 0; i < tables.length; i++) {
 
            // Get the ith table
            var table = tables[i];
 
            // Set the id dynamically
            table.setAttribute("id", i + 1);
 
            // The line below will also give id
            // dynamically to the tables
            //table.id = i+1;
        }
    </script>
</body>
 
</html>


Output: The two tables will be created with “id”s 1 and 2 respectively.

RELATED ARTICLES

Most Popular

Dominic
32514 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6891 POSTS0 COMMENTS
Nicole Veronica
12012 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12105 POSTS0 COMMENTS
Shaida Kate Naidoo
7016 POSTS0 COMMENTS
Ted Musemwa
7262 POSTS0 COMMENTS
Thapelo Manthata
6975 POSTS0 COMMENTS
Umr Jansen
6962 POSTS0 COMMENTS