Hide (X)HTML Row with Javascript
by Brandon on Sep 7th in JavaScript
As posted on code society, here is a simple tutorial on hiding content – or in this case a row in a table using javascript.
<table>
<tr id="idRow">
<td>ROW1</td>
</tr>
<tr>
<td>ROW2</td>
</tr>
<tr>
<td>ROW3</td>
</tr>
</table>Theres the table. The row which we want to hide is given an id so we can refer back to it later in the javascript.
Heres the javascript
function hideRow() { var row = document.getElementById("idRow"); row.style.display = 'none'; }
We locate the ID from the document we are using (HTML page) and place it into a variable – in this case called row. We then give it the [i]none[/i] style property value to hide the row or give it a “no display”.
Improving upon that, we could even check to see the current display property value of the id with the following.
function hideRow() { var row = document.getElementById("idRow"); if (row.style.display == '') { row.style.display = 'none'; } else { row.style.display = ''; } }
What happened here is that we checked to see if the display property for row was set to nothing or not to none first. If it was not none, then set it to it. If the row display property was already hidden, remove the none and show the row once more.
Here is a full example with the Javascript emmbedded into the header.
<html> <head> <title>bluecapstudio.com - Hide Row with JavaScript</title> <script type="text/javascript"> function hideRow() { var row = document.getElementById("captionRow"); if (row.style.display == '') { row.style.display = 'none'; } else { row.style.display = ''; } } </script> </head> <body> <table> <tr id="idRow"> <td>ROW1</td> </tr> <tr> <td>ROW2</td> </tr> <tr> <td>ROW3</td> </tr> </table> <button onclick="hideRow()" >CLICK ME</button> </body> </html>