I have a HTML table generated with a <asp:GridView/>
object via a VB.Net call that populates the table from a database query.
The result is a table like this:
<table id="myTab">
<tr><td>val1</td></tr>
<tr><td>val2</td></tr>
.
.
<tr><td>valN</td></tr>
The javascript code is on a button :
function toggleHide(val) {
tb = getElementById("myTab");
if ( tb != null ) {
trows = tb.rows;
for ( var i = 0; i< trows.length; i++ ) {
if ( trows[i].cells[0].innertText == val ) {
trows[i].style.display = 'none';
}
else {
trows[i].style.display = '';
}
}
}
return false;
}
This works well with smaller volumes of data, but once we get over 100 it simply stops processing/crashes, leaving the page blank.
I get it that accessing the DOM repeatedly like this might be slow. is there an alternative faster way?
3
Answers
If the values inside the cells are known before-hand, and limited, @C3roe’s comment is the best solution.
Otherwise, if you’re looking for something dynamic for any text, try this:
'tr[data-txt*="'+txt+'"]{ display: none; }'
Full example and related fiddle for 10.000 rows. Try it out with any size you want:
You could use querySelectorAll() to get all the table rows first this will reduce your calls to DOM and make your code a lot faster.
It shouldn’t be that slow. I suspect that every button click iterates through all rows of the table. This is not very efficient.
First: you can use event delegation to make handling more efficient.
Second: use a css class for the hiding.
Third: try limiting the number of iterations through the rows to a minimum (e.g. by using
querySelectorAll
and more precize css selectors).Here’s an example for a few scenario’s with the aformentioned in mind.