简体   繁体   中英

What's the fastest way of hiding and showing all the rows of a table in javascript?

I am building a filter for querying our html table (10k+ rows). My initial thought was to first hide all the rows, and then unhide the rows that match the specific query. If the filter is removed, then show all rows.

Is this a more optimal way of writing the hide/show all rows functions?

// optimize this!
this.hideAllRows = function() {
    nodes = document.getElementById('table_body').children
    for(var i=0, i_max=nodes.length; i<i_max; i++) {
        nodes[i].style.display="none"
    }
}

// optimize this!
this.showAllRows = function() {
    nodes = document.getElementById('table_body').children
    for(var i=0, i_max=nodes.length; i<i_max; i++) {
        nodes[i].style.display=""
    }
}

Thanks!

One solution would be to implement a pagination or "infinite" scroll feature. This would remove the need to render 10k dom elements simultaneously. You could render them in batches, as the user scrolls, or chunk them into pages.

Alternatively, you can try pulling the table out of the dom, hiding rows, then reinserting it. This will prevent unneccesary reflows/paints/etc.

As a rule of thumb using a pure javascript for loop is faster than using jQuery .each() but your basic selection using the .getElementById() and .children property is already well optimized.

However iterating through 10k+ elements in the browser is always going to be slow. Showing and hiding elements is best suited to record sets in the 100s not the 1000s.

Why not make an AJAX request that returns data (presumably from a database) already formated as <tr>...some <td>s here....</tr><tr>...some <td>s here....</tr> ?

That way you can let your database do all the heavy lifting when it comes to filtering, they are optimized to do this. It keeps your code is simple, your bandwidth is reduced, and your DOM manipulation is kept to a minimum.

Whenever you want to apply a filter, you can make a $.ajax request.

function filter(criteria){

    $.ajax({
        url : myDataUrl,
        type : "POST",
        data : {criteria : criteria}
    })
    .success(function (data){
        $("#table-body").html(data);
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM