views:

66

answers:

3

Without Jquery or any JavaScript library i need to hide the rows of a simple html table except for the table head on page load.

+1  A: 

No particular need to resort to javascript, you can do the trick through CSS too:

#table_id tr
{
  display:none;
}

This should hide all TRs not TH.

Sarfraz
From an accessibility point of view, you should not hide data which are likely to be never showed without the use of javascript.
Boris Guéry
+4  A: 

if your table is correctly marked up. You can do something like :

document.getElementById('yourtable')
        .getElementsByTagName('tbody')[0]
        .style.display = 'none';

Then put this on an 'onload' event

You could also do it in CSS + Javascript by setting a global .js class to your tag and then use CSS selector.

html.js #yourtable tbody 
{
   display: none;
}
Boris Guéry
OP says "Without Jquery or any JavaScript library", he wants a solution with javascript.
Sarfraz
+1  A: 
<style type="text/css">
.mytable tr {
    display: none;
}
</style>

Just kidding. Here we go:

<table border="1" id="mytable">
<th>
    <td>asd</td>
    <td>asd</td>
</th>
<tr>
    <td>asdkjas</td>
    <td>asdasdjwa</td>
</tr>
<tr>
    <td>asdkjas</td>
    <td>asdasdjwa</td>
</tr>
</table>

<script type="text/javascript">
window.onload=function(){
    hideTableRows();
}
function hideTableRows() {
    var myTableRows = document.getElementById("mytable").getElementsByTagName("tr");
    for(i=0;i< myTableRows.length;i++) {
        myTableRows[i].style.display = "none";
    }
}
</script>

I think a table requires rows, won't display with just headers.. I could suggest adding a blank row at the start of the table, and changing "i" in the for loop to 1. That way the first row should be skipped.

HTH Marko

Marko
Damn I'm slow. :)
Marko