Toggle Show And Hide Only Some Table Rows
12,189
Your approach seems ok, i suggest you declare variables tr
and i
alternately you could use class
instead
<span onclick="toggle('yes');">
if (tr[i].className == thisname){
<tr class=yes>
Author by
ONDEV
Updated on June 14, 2022Comments
-
ONDEV about 2 years
I am trying to show/hide (via a toggle mechanism) only certain rows in my table. I have gotten somewhat close, code is below. What I was reading about in other questions regarding this is the use of style id's and I have tried that but it fails for me. So that is why I used 'hide=yes' and pass that into the toggle function.
This is going to be a table with a couple of hundred entries that when I click toggle can be reduce down to less than 30 on any given day.
Is there a better way to do this?
<html> <head> <script> function toggle(thisname) { tr=document.getElementsByTagName('tr') for (i=0;i<tr.length;i++){ if (tr[i].getAttribute(thisname)){ if ( tr[i].style.display=='none' ){ tr[i].style.display = ''; } else { tr[i].style.display = 'none'; } } } } </script> </head> <body> <span onClick="toggle('hide');">TOGGLE</span><br /><br /> <table> <tr ><td >display this row 1</td></tr> <tr hide=yes ><td>hide this row 1</td></tr> <tr><td>display this row 2</td></tr> <tr hide=yes ><td>hide this row 2</td></tr> <tr hide=yes ><td>hide this row 3</td></tr> <tr><td>display this row 3</td></tr> <tr><td>display this row 4</td></tr> <tr><td>display this row 5</td></tr> <tr><td>display this row 6</td></tr> <tr hide=yes ><td>hide this row 4</td></tr> <tr hide=yes ><td>hide this row 5</td></tr> <tr><td>display this row 7</td></tr> <tr hide=yes ><td>hide this row 6</td></tr> <tr hide=yes ><td>hide this row 7</td></tr> </table> </body> </html>
-
ONDEV over 12 yearsYes, this works. Thank you. Is it better to use classname from a perspective of speed or readability, both?
-
david over 12 yearsGetting the className would be faster than finding the attributes value i think, you can do some tests to be sure for the speed