There are several issues:
- Class names (and IDs) are not allowed to start with a digit.
- You have to pass a class to
getElementsByClassName()
.
- 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";
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…