add class tr datatable

How to Add Class "tr datatable" in HTML

Adding class "tr datatable" to an HTML element is a simple task. This class has a special purpose, it helps us to style tables in our web page. I will show you how to do it using two different ways.

Method 1 - Using HTML

To add class "tr datatable" to a table row (tr) using HTML, we need to modify the opening tr tag. We can do it in two ways.

Method 1.1 - Adding Class Attribute Directly

We can add the class attribute directly to the opening tr tag and set its value as "tr datatable". Here is the code:


<table>
  <tr class="tr datatable">
    <td>Column 1</td>
    <td>Column 2</td>
  </tr>
</table>

In this code, we have added the class attribute directly to the opening tr tag and set its value as "tr datatable". The td tags are just for demonstration purposes.

Method 1.2 - Adding Multiple Classes

We can also add multiple classes to an HTML element. To do this, we need to separate each class name with a space. Here is the code:


<table>
  <tr class="tr header datatable">
    <td>Column 1</td>
    <td>Column 2</td>
  </tr>
  <tr class="tr datatable">
    <td>Data 1</td>
    <td>Data 2</td>
  </tr>
</table>

In this code, we have added two classes to the first tr tag. We have added the "tr" class for styling the table rows and the "header" class for styling the header row. The second tr tag just has the "tr" class.

Method 2 - Using JavaScript

If we want to add class "tr datatable" to a tr tag dynamically using JavaScript, we can do it using the classList property. Here is the code:


<table id="mytable">
  <tr>
    <td>Column 1</td>
    <td>Column 2</td>
  </tr>
</table>

<script>
  var table = document.getElementById("mytable");
  var row = table.rows[0];
  row.classList.add("tr", "datatable");
</script>

In this code, we have added id "mytable" to the table element for easy identification. In the script section, we have used the getElementById method to get a reference to the table element. We have then used the rows property to get a reference to the first row (index 0) of the table. Finally, we have used the classList property to add two classes to the row - "tr" and "datatable".

That's it! We have successfully added class "tr datatable" to a table row using two different ways - HTML and JavaScript.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe