How to useclassList Method in Javascript

Similar to the first approach, this method uses the classList property of an HTML element. However, instead of using the add method, it directly adds a class using the classList property. Suitable when you prefer a concise method to directly add a class to an element.

Example: In this example we are using ClassList Method.

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0">
    <title>Dynamic Table</title>
    <style>
        .dynamicTableMethod {
            /* Define your styles for dynamicTableMethod class */
        }
    </style>
</head>
 
<body>
 
    <button onclick="addRowWithClassListMethod()">
      Add Row (classList Method)
      </button>
    <table id="myTableMethod" class="dynamicTableMethod">
        <!-- Existing Table Content Goes Here -->
    </table>
 
    <script>
        let rowCountClassListMethod = 1;
 
        function addRowWithClassListMethod() {
            const table = document.getElementById("myTableMethod");
            const newRow = table.insertRow(-1);
            newRow.classList.add("dynamicTableMethod");
            const cell = newRow.insertCell(0);
            cell.innerHTML = "Row " + rowCountClassListMethod++;
        }
    </script>
 
</body>
 
</html>


Output:

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 adding “id”s dynamically.

Below are the approaches used to dynamically insert id into table elements using JavaScript:

Table of Content

  • Using classList Object
  • Using classList Method
  • Using id Property

Similar Reads

Approach 1: Using classList Object

This approach utilizes the classList object to add a class to a dynamically created table row. The class is added using the add method. Useful when you want to apply styles or behavior to multiple rows that share the same class....

Approach 2: Using classList Method

...

Approach 3: Using id Property

Similar to the first approach, this method uses the classList property of an HTML element. However, instead of using the add method, it directly adds a class using the classList property. Suitable when you prefer a concise method to directly add a class to an element....