I coded a php page that displays information from a mysql database neatly into tables. I would like to hide empty table rows with an onLoad event handler.
Here is a sample table with code that hides a <td>
when it has no content. but i can only get it to work with different IDs:
<script type="text/javascript">
function hideTd(id){
if(document.getElementById(id).textContent == ''){
document.getElementById(id).style.display = 'none';
}
}
</script>
</head>
<body onload="hideTd('1');hideTd('2');hideTd('3');">
<table border="1">
<tr>
<td id="1">not empty</td>
</tr>
<tr>
<td id="2"></td>
</tr>
<tr>
<td id="3"></td>
</tr>
</table>
</body>
what i want to do is use a class for the <td>
s to achieve the same thing while only referencing the class once, and not referencing every single id that I want to remove, which will not even work for my dynamic content. I tried using this code:
<script type="text/javascript">
function hideTd(){
if(document.getElementsByClassName().textContent == ''){
document.getElementsByClassName().style.display = 'none';
}
}
</script>
</head>
<body onload="hideTd('1');">
<table border="1">
<tr>
<td class="1">not empty</td>
</tr>
<tr>
<td class="1"></td>
</tr>
<tr>
<td class="1"></td>
</tr>
</table>
</body>
but it does not work. its supposed to hide the empty <td>
s that have the specified class. how do i hide empty <td>
s using classes, not IDs?
This question is related to
javascript
webforms
html-table
dynamic-data
If you want to do it by ClassName you could do:
<script type="text/javascript">
function hideTd(className){
var elements;
if (document.getElementsByClassName)
{
elements = document.getElementsByClassName(className);
}
else
{
var elArray = [];
var tmp = document.getElementsByTagName(elements);
var regex = new RegExp("(^|\\s)" + className+ "(\\s|$)");
for ( var i = 0; i < tmp.length; i++ ) {
if ( regex.test(tmp[i].className) ) {
elArray.push(tmp[i]);
}
}
elements = elArray;
}
for(var i = 0, i < elements.length; i++) {
if( elements[i].textContent == ''){
elements[i].style.display = 'none';
}
}
}
</script>
Source: Stackoverflow.com