Search code examples
javascripthtmlchildren

HTML finding and stop displaying table child


I've done this:

<table id="tabla">
    <tbody>
        <tr><th>row1</th><td>w</td></tr>
        <tr><th>row2</th><td>x</td></tr>
    </tbody>
    <tbody>
        <tr><th>row1</th><td>y</td></tr>
        <tr><th>row2</th><td>z</td></tr>
    </tbody>
</table>

<script type="text/javascript">
    function iterate() {
        var table = document.getElementById("tabla").children;
        for (b=0; b<table.length(); b++) {
            var cells = table[b].children;
            if(cells[0].innerHtml == "row1") {
                if(cells[1].innerHtml == "w") {
                    table[b].style.display="none";
                }
            }
        }
    }
</script>

My intention is to find all children of the table that satisfy a condition and to stop displaying them.

My code is not working, I do not know why.

Does anyone know?


Solution

    1. The children of your table element are tbody
    2. There is no length() function, it's an attribute (just use length)
    3. There is no innerHtml, you should use innerHTML
    4. The cells[0] you refer to is actually the row (and not the cell) so it's innerHTML == <th>row1</th><td>w</td>

    Here is the fix to your code:

    function iterate() {
      var table = document.getElementById("tabla").children;
      for (b=0; b<table.length; b++) {
        var rows = table[b].children;
        for (r=0; r<rows.length;r++) {
          var cells = rows[r].children
          if (cells[0].innerHTML == "row1") {
            if (cells[1].innerHTML == "w") {
              table[b].style.display="none";
            }
          }
        }
      }
    }
    
    iterate();
    <table id="tabla">
        <tbody>
            <tr><th>row1</th><td>w</td></tr>
            <tr><th>row2</th><td>x</td></tr>
        </tbody>
        <tbody>
            <tr><th>row1</th><td>y</td></tr>
            <tr><th>row2</th><td>z</td></tr>
        </tbody>
    </table>