Hide Table Columns with JavaScript
Update: I finally got around to writing a new version of this with jQuery, check out the new post Hiding Table Columns with jQuery.
Here is a little JavaScript function I whipped up last night. I’m working on a large loan-processing site, and thought it would be nice to be able to hide certain columns when viewing lots of loans on the same page. Here is the function:
function hideCol(strCol){
var ths = document.getElementsByTagName("th");
var tds = document.getElementsByTagName("td");
for (idx in ths){
if (ths[idx].className == strCol)
ths[idx].className = “hidden”;
}
for (idx in tds){
if (tds[idx].className == strCol)
tds[idx].className = “hidden”;
}
}
To use the function, just give each of the td’s and th’s in the column the same class name. Then add a link that calls “javascript:hideCol(’columnName’);”. You will also need to define a CSS rule “.hidden {display:none;}”.
This works especially well with scripted table building, such as dumping lots of rows from a database. It makes adding the class name much easier.
Downsides:
- The function only hides the column, once the classname has been changed to hidden, there is no way to display the columns, other than looking through table cells for those with the hidden class and removing it.
- The columns re-appear on a page refresh. The next logical step would be to use a cookie to store user the user’s preferences.
Update:
I just discovered that browsers will support multiple classes, this will allow hiding and restore of colums all without a refresh, I’ll post an updated version of the function soon.
Abdinoor is god.
Nice script - after searching for a couple of hours, I came upon this - easy to implement, easily explained, and perfect for my purpose. Thanks!
Hi
Did you ever do the updated routine that will allow hiding and restore of colums all without a refresh
Andy
[...] ago I wrote a post called Hide Table Columns with JavaScript and I have wanted to write an updated version ever since. The original solution is rather naive and [...]