Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

test if first child

Tags:

jquery

I'm testing to see if a row in a table is the first child. So far I have:

    //the loop works
$('#GridFolderPopup').find('tr').each(function () {

    if ( $(this).is(:first) == true ) //this is the faulty line
    {
         $(this).addClass('GridFolderRow');
    };
});

Any suggestions?

Thanks

like image 560
frenchie Avatar asked Feb 16 '11 04:02

frenchie


People also ask

What is first child in css?

The :first-child selector allows you to target the first element immediately inside another element. It is defined in the CSS Selectors Level 3 spec as a “structural pseudo-class”, meaning it is used to style content based on its relationship with parent and sibling content.

What is firstChild?

firstChild returns the first child node (an element node, a text node or a comment node). Whitespace between elements are also text nodes. firstElementChild returns the first child element (not text and comment nodes).

Is first child jQuery?

It is a jQuery Selector used to select every element that is the first child of its parent. Return Value: It selects and returns the first child element of its parent.


1 Answers

Simply asking for the first child of the table/tbody is much more efficient than testing every single row in it. The larger the table, the bigger the difference.

Therefore :

  • if you want to "see if a [given] row in a table is the first child":

    if ($(a_given_row).prev().length === 0) {
        // no element before this row, so it's the first one.
    }
    
  • if you want to get the first row of a table:

    // Directly ask the DOM for the first element child of the table/tbody
    var firstRow = a_given_table.firstChild;
    do {
       firstRow = firstRow.nextSibling;
    } while (firstRow.nodeType !== 1)
    
    // If you don't need to support IE8-, you can use this single line instead:
    var firstRow = a_given_table.firstChildElement;
    

    See performance comparison here: http://jsperf.com/get-first-child-element

like image 185
marcv Avatar answered Oct 29 '22 01:10

marcv