Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toggle a table <tr>'s display:none using Javascript

I would like to use JavaScript to make a table row's display:none; and show it again on a click of a button.

like image 549
Varada Avatar asked Jul 25 '26 22:07

Varada


2 Answers

Plain JS - delegation, can handle dynamically inserted rows

window.addEventListener("DOMContentLoaded", function() {
  document.getElementById("nav").addEventListener("click", function(e) {
    var tgt = e.target;
    if (tgt.tagName === "A") {
      e.preventDefault(); // stop click
      var  rowId = tgt.getAttribute("data-id"),
        rowIndex = tgt.getAttribute("data-index"),
             row = rowId ? document.getElementById(rowId) : // id passed 
      document.getElementById('table1').rows[rowIndex - 1]; // idx passed
      if (row) row.style.display = (row.style.display == 'none') ? '' : 'none';
    }
  });
});
<div id="nav">
  <a href="#" data-id="row3">Toggle row with ID row3</a> | 
  <a href="#" data-index="2">Toggle 2nd row</a><hr/>
  
</div>

<table>
<tbody id="table1">
<tr><td>row 1 cell 1</td><td>row 1 cell 2</td><td>row 1 cell 3</td></tr>
<tr><td>row 2 cell 1</td><td>row 2 cell 2</td><td>row 2 cell 3</td></tr>
<tr id="row3"><td>row 3 cell 1</td><td>row 3 cell 2</td><td>row 3 cell 3</td></tr>
</tbody>
</table>

Plain JS - inline handler can ALSO handle dynamically inserted rows but the above is preferred

function toggle(row) {
  if (isNaN(row)) row = document.getElementById(row); // id passed
  else row = document.getElementById('table1').rows[row]; // idx passed
  if (row) row.style.display = (row.style.display == 'none') ? '' : 'none';
  return false;
}
<a href="#" onClick="return toggle('row3')">Toggle row with ID row3</a> | 
<a href="#" onClick="return toggle(1)">Toggle 2nd row</a><hr/>

<table>
<tbody id="table1">
<tr><td>row 1 cell 1</td><td>row 1 cell 2</td><td>row 1 cell 3</td></tr>
<tr><td>row 2 cell 1</td><td>row 2 cell 2</td><td>row 2 cell 3</td></tr>
<tr id="row3"><td>row 3 cell 1</td><td>row 3 cell 2</td><td>row 3 cell 3</td></tr>
</tbody>
</table>
like image 191
mplungjan Avatar answered Jul 28 '26 12:07

mplungjan


You have to modify the style attribute of the element:

// `rowElement` is a reference to the row you want to hide
rowElement.style.display = 'none';
like image 24
Felix Kling Avatar answered Jul 28 '26 10:07

Felix Kling



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!