Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
187
rated 0 times [  193] [ 6]  / answers: 1 / hits: 150020  / 14 Years ago, wed, july 28, 2010, 12:00:00

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?


More From » webforms

 Answers
7

There are several issues:




  1. Class names (and IDs) are not allowed to start with a digit.

  2. You have to pass a class to getElementsByClassName().

  3. You have to iterate of the result set.



Example (untested):



<script type=text/javascript>
function hideTd(className){
var elements = document.getElementsByClassName(className);
for(var i = 0, length = elements.length; i < length; i++) {
if( elements[i].textContent == ''){
elements[i].style.display = 'none';
}
}

}
</script>
</head>
<body onload=hideTd('td');>
<table border=1>
<tr>
<td class=td>not empty</td>
</tr>
<tr>
<td class=td></td>
</tr>
<tr>
<td class=td></td>
</tr>
</table>
</body>


Note that getElementsByClassName() is not available up to and including IE8.



Update:



Alternatively you can give the table an ID and use:



var elements = document.getElementById('tableID').getElementsByTagName('td');


to get all td elements.



To hide the parent row, use the parentNode property of the element:



elements[i].parentNode.style.display = none;

[#96096] Saturday, July 24, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
andrewb

Total Points: 259
Total Questions: 124
Total Answers: 90

Location: Ivory Coast
Member since Sun, Mar 7, 2021
3 Years ago
;