Skip to content
Related Articles

Related Articles

How to dynamically insert id into table element using JavaScript ?
  • Last Updated : 18 Nov, 2020

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 Genrated ID")
  • It can also be done by accessing the “id” of the selected element (table).
    table.id = "Dynamically Genrated ID";

Example:

HTML

filter_none

edit
close

play_arrow

link
brightness_4
code

<!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>

chevron_right


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

full-stack-img




My Personal Notes arrow_drop_up
Recommended Articles
Page :