Search code examples
javascriptjqueryjquery-selectorsnested-table

Selector: Fastest way to get descendants of a specific level only


I have a table like:

<table id="table">
    <tbody>
        <tr></tr>
        <tr>
            <td>
                <table>
                    <tbody>
                        <tr></tr>
                    </tbod>
                </table>
            </td>
        </tr>
     </tbody>
</table>

I'm using jQuery and there exists a stored selector to get the most outer table:

var x = $('#table')

Starting from that If want to get all first level <tr>-elements.

If I use one of those:

x.find('tbody > tr');
x.children('tbody').children();

… the first one will naturally select all nested <tr>-elements as well. The latter seems over-complicated and involves multiple queries.

Is there a way to make this faster/more efficient?


Solution

  • First thing, x.find('tbody > tr') would find all <tr>s. You would need to do x.find('> tbody > tr'), assuming x is x from your example.

    I ran a test and this with both and this was my finding.

    .children(): 3.013ms
    >: 0.626ms
    

    so the > method is faster than the .children() method. The function calls add up... barely.

    Here's my JavaScript for the testing.

    var $table = $('#table'), $usingChildren, $usingAngleBracket;
    
    console.time('.children()');
    $usingChildren = $table.children('tbody').children('tr');
    console.timeEnd('.children()');
    
    console.time('>');
    $usingAngleBracket = $table.find('> tbody > tr');
    console.timeEnd('>');
    
    console.log( $usingChildren, $usingAngleBracket );