Skip to content
Related Articles

Related Articles

Improve Article

How to dynamically insert id into table element using JavaScript ?

  • Last Updated : 29 May, 2021

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.

Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :