Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Show / Hide HTML Table rows using Javascript

I don’t know why something this simple isn’t working.

<table id="df">
  <tr><td>foo</td></tr>
  <tr><td>bar</td></tr>
  <tr><td>abc@yahoo.com</td></tr>
</table>

Say we have an HTML table. How would I hide all rows / only some rows, and vice versa, how would I show all rows / only some rows?

Things that aren’t working:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

//one

document.getElementByTagName('table').style.display = "none";

//two

var rows = document.getElementsByTagName("table")[0].rows;
rows.hidden = false;

//three

var table = document.getElementById("df");
table.style = "display:table-row";

Thanks in advance

>Solution :

You can select row n using nth-child css selector

const table = document.querySelector("#df tbody")

const toggleRow = (rowIndex = 0) => {
  if (table.childElementCount < rowIndex) return

  const row = table.querySelector(`:nth-child(${rowIndex})`)

  row.style.display = row.style.display === 'none' ? 'block' : 'none'
}

toggleRow(1) // Hide first row
toggleRow(2) // Hide second row
toggleRow(4) // Will not hide because because table only have 3 rows
toggleRow(2) // Show second row
<table id="df">
  <tbody>
    <tr>
      <td>foo</td>
    </tr>
    <tr>
      <td>bar</td>
    </tr>
    <tr>
      <td>abc@yahoo.com</td>
    </tr>
  </tbody>
</table>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading