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
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.
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).
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With