I'm generating a phone list from Active Directory records and I want to hide rows in my table that don't have an entry for ipPhone (column 5 of my table).
My Javascript is essentially like this:
table = document.getElementById("myTable1");
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td");
dbg = td[5].innerHTML; // <<< Error here.
if (dbg == "") {
tr[i].style.display = "none";
}
}
<table id="myTable1" border="1">
<tr>
<td>Martin</td>
<td>Roger</td>
<td>Operator</td>
<td></td>
<td>Office</td>
<td id="ipPhone"></td>
<td></td>
<td>Ronan.Martina@mydomain.com</td>
<td>martinro</td>
<td></td>
</tr>
</table>
Chrome's debugger is giving me:
Uncaught TypeError: Cannot read properties of undefined (reading 'innerHTML')
and none of the rows are hidden.
Can anyone spot the problem?
try that:
const myTable = document.getElementById('myTable1');
myTable
.querySelectorAll(' tr > td:nth-of-type(5):empty')
.forEach( td5 =>
{
td5.closest(('tr').style.display = 'none';
})
You cannot have more than a single element in a page with id="ipPhone". This must be fixed.
Use a CSS class instead, and instead of wiggling with indexes, use a much more readable and easier way of looping:
for (const cell of document.querySelectorAll("#myTable1 td.ipPhone")) {
cell.parentElement.hidden = !cell.textContent;
}
With selectors level 4 you will be able to achieve this using CSS only:
tr:has(td.ipPhone:empty) { display: none; }