Monday, February 07, 2005

Hiding and showing rows in IE and Mozilla/FireFox

One issue that a web developer may run into is how to toggle hiding/showing a row in an HTML table using JavaScript that works in both sets of browsers: Internet Explorer and Mozilla/FireFox/Netscape. In IE, you can set the style.display to "none" for the row, but this doesn't work in Mozilla.

One approach that woks in both browsers is to dynamically assign the class for the row using the following css styles:

<style>
.hide {display: none;}
.show {display: table-row;}
</style>

And here is the entire html for a test page that demonstrates using this approach....

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<html>

    <head>

        <title>Hiding tables rows in IE and Mozilla!</title>

        <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1">

        <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">

<style>

 

.hide {display: none;}

 

.show {display: table-row;}

 

</style>

 

<script>

 

var myBody;

 

function start() {

    // get a list of all the body elements (there will only be one)

    myDocumentElements=document.getElementsByTagName("body");

    // the body element itself is the first item of the list

    myBody=myDocumentElements.item(0);

}

 

function hideRow() {

    mytable=myBody.getElementsByTagName("table").item(0);

    mytablebody=mytable.getElementsByTagName("tbody").item(0);

    myrow=mytablebody.getElementsByTagName("tr").item(0);

 

    myrow.className="hide";

 

 

}

 

function showRow() {

    mytable=myBody.getElementsByTagName("table").item(0);

    mytablebody=mytable.getElementsByTagName("tbody").item(0);

    myrow=mytablebody.getElementsByTagName("tr").item(0);

    myrow.className="show";

 

}

</script>

 

    </head>

    <body onload="start()">

        <P>Hiding tables rows in IE and Mozilla!</P>

 

        <TABLE border="5" ID="Table1" >

        <tbody>

            <tr >

                <td >cell is row 0 column 0 </td>

                <td >cell is row 0 column 1 </td>

            </tr>

            <tr >

                <td >cell is row 1 column 0 </td>

                <td >cell is row 1 column 1 </td>

            </tr>

        </tbody>

        </TABLE>

        <BR>

        <INPUT id="cmdHide" type="button" value="Hide Table Row" name="cmdHide" onclick="hideRow()">

        <INPUT id="cmdShow" type="button" value="Show Table Row" name="cmdShow" onclick="showRow()">

    </body>

</html>

No comments: