Loop through Table and set Checkboxes to True

Loop through Table and set Checkboxes to True

by Nirvanachain

HTML

<table>
    <tr>
        <td><input type="checkbox" /></td>
        <td>One</td>
    </tr>
    <tr>
        <td><input type="checkbox" /></td>
        <td>Two</td>
    </tr>
    <tr>
        <td><input type="checkbox" /></td>
        <td>Three</td>
    </tr>
    <tr>
        <td><input type="checkbox" /></td>
        <td>Four</td>
    </tr>
    <tr>
        <td><input type="checkbox" /></td>
        <td>Five</td>
    </tr>    
</table>

JavaScript

(function() {
    var table = document.querySelector('table'); //Select <table>
    var i;
    
    var rowLength = table.rows.length;  //Length of rows in <table>
    
    for(i = 0; i < rowLength; i++) {
      var tableCells = table.rows.item(i).cells; //Store the contents of earch row in an array.
      console.log('tableCells = ' + tableCells);
        if (tableCells[1].textContent === 'One' || tableCells[1].textContent === 'Three') {
            //If the text in the second <td> is 'One' or 'Three' set the Checkboxes checked property to true.  textContent property is supported in Chrome.
            tableCells[0].querySelector('input').checked = true;
        }
     
    };
})();