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:
//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>