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.


  • 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). = "Dynamically Generated ID";



<!DOCTYPE html>
        td {
            border: 1px solid black;
            border-collapse: collapse;
            margin: auto;
            width: 50%;
            text-align: center;
    <h1 style="color:green;text-align: center;">
        // Getting the table element
        var tables = document
        // 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
            // = i+1;

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 :