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