Can I suggest something like this?
$(function() { $('#show').click(function() { var i; for (i = 0; i < titles.length; i++) { ToggleHeadVisibility('SHOW', titles[i]); } }); $('#hide').click(function() { var i; for (i = 0; i < titles.length; i++) { ToggleHeadVisibility('HIDE', titles[i]); } }); }); var titles = ['one', 'three', 'five']; function ToggleHeadVisibility(showHide, title) { var x = $('th[title=' + title + ']').index(); var selectString = 'th:nth-child(' + (x + 1) + '), td:nth-child(' + (x + 1) + ')'; var $set = $(selectString); if (showHide === "SHOW") { $set.show(); } else if (showHide === "HIDE") { $set.hide(); } }
I think that, in fact, is your loop, that is the problem. You repeat everything in the table. If you only want to find specific ones, why not just sort through the ones you want to find?
So what is going on here is exactly the case. When you click the "show" (or "hide") button, we iterate over the array of titles, calling ToggleHeadVisibility.
In this function, we get the index of the first element with this header, and then show or hide the nth-child (x) nodes.
I ran it on a table with 6 columns, showing and hiding 3 at a time, and more than 1000 rows. This is pretty fast for what he is doing.
Please note that if your headers are not unique, it will only find the first one in the table.
Ryan kinal
source share