How to show / hide hidden rows of HTML table using JavaScript (no jQuery)
Edit: This was given below.
I would like to have an HTML table that contains hidden lines between each line with additional information about the top level rows. Clicking on the flip / crash link in the first column toggles the visibility of the hidden row from the screen: none; for display: table-row ;. I haven't written JavaScript in a while and should be able to do it strictly in JavaScript and cannot use jQuery's toggle () method.
How can I use JavaScript to find a sibling with class = "subRow" with class = "parentRow" that the button is inside the table and then toggles the visibility of that sibling row?
Html
<table style="width:50%">
<caption>Test Table</caption>
<thead>
<tr align="center">
<th><span class="offscreen">State Icon</span></th>
<th>Column 2</th>
<th>Column 3</th>
<th>Column 4</th>
<th>Column 5</th>
</tr>
</thead>
<tbody>
<tr align="center" class="parentRow">
<td><a href="#" onclick="toggleRow();"><img alt="Expand row" height="20px;" src="expand.png"></a></td>
<td>test cell</td>
<td>test cell</td>
<td>test cell</td>
<td>test cell</td>
</tr>
<tr style="display: none;" class="subRow">
<td colspan="5"><p>Lorem ipsum dolor sit amet...</p></td>
</tr>
....
</tbody>
</table>
CSS
.offscreen {
position: absolute;
left: -1000px;
top: 0px;
overflow:hidden;
width:0;
}
.subRow {
background-color: #CFCFCF;
}
JavaScript
function toggleRow() {
var rows = document.getElementsByClassName("parentRow").nextSibling;
rows.style.display = rows.style.display == "none" ? "table-row" : "none";
}
source to share
Pass the event handler a reference to the string that was clicked with this
:
<td><a href="#" onclick="toggleRow(this);"><img alt="Expand row" height="20px;" src="expand.png"></a></td>
Then update the toggleRow function as follows:
function toggleRow(e){
var subRow = e.parentNode.parentNode.nextElementSibling;
subRow.style.display = subRow.style.display === 'none' ? 'table-row' : 'none';
}
You might want to consider creating a generic function for navigating the DOM tree (so that this functionality is not broken when the HTML code changes).
source to share
Use id attribute to get elements instead of class and give any string a unique id in it to make them different.
<tr style="display: none;" class="subRow" id="subRow1">
.
.
.
<tr style="display: none;" class="subRow" id="subRow2">
.
.
<tr style="display: none;" class="subRow" id="subRow3">
source to share