Search code examples
javascripthtmlcss

How to remove all <td> style of a specific table?


I have this table "wordTable". Each <td> has an id.

<table id="wordTable">
<tr>
<td id="1">ac</td>  <td id="2">bd</td>
</tr>
<tr>
<td id="3">bf</td>  <td id="4">uy</td>
</tr>
<tr>
<td id="5">ca</td><td></td>
</tr>
</table>

Some <td> got its style changed ramdomly. For example

document.getElementById("1").style.color ="red";

document.getElementById("3").style.color ="blue";

document.getElementById("2").style.color ="green";

How to remove all style of table "wordTable" so that the table becomes to its original state?

Maybe something like this document.getElementById('wordTable').TD. removeStyle();


Solution

  • You can remove the inline style of each element within the table by looping through all elements and setting their style attribute to an empty string.

    Demo:

    document.getElementById("1").style.color ="red";
    
    document.getElementById("3").style.color ="blue";
    
    document.getElementById("2").style.color ="green";
    
    
    //get all <td> elements within the table with id 'wordTable'
    var tdElements = document.querySelectorAll('#wordTable td');
    
    //loop through each <td> element and remove its inline style
    tdElements.forEach(function(td) {
        td.style = '';
    });
    <table id="wordTable">
      <tr>
        <td id="1">ac</td>  <td id="2">bd</td>
      </tr>
      <tr>
        <td id="3">bf</td>  <td id="4">uy</td>
      </tr>
      <tr>
        <td id="5">ca</td><td></td>
      </tr>
    </table>