Search code examples
javascriptinnerhtml

Change innerHTML in all <td> rows


How to change innerHTML in all rows?

This script only changes innerHTML in first row.

<table>
<tr><td id="X">0</td></tr>
<tr><td id="X">0</td></tr>
</table>

<script>
if (document.getElementById("X").innerHTML == 0)
{ 
document.getElementById('X').innerHTML = '1';
} 
</script>


Solution

  • First of all you should not give same 'id' attribute multiple time in DOM. Bad practice. you can assign same 'class' instead.

    But even if this is the set elements with you then using following code will solve your problem

    var tdList = document.getElementsByTagName('td');
    for(var i=0; i< tdList.length; i++){ 
      if(tdList[i].innerHTML.trim()=='0' && tdList[i].getAttribute('id') == "X")
      tdList[i].innerHTML = '1' 
    }