Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does $('#table > tr') selector not match? (always return 0)

The html code:

<table id='table'>
    <tr>
        <td>..</td>
    </tr>
</table>

The js code with jquery:

var l1 = $('#table > tr').length;
var l2 = $('#table tr').length;
alert(l1+','+l2);​

The result:

 0,1

Why the first #table > tr get 0?

You can see a live demo from here: http://jsfiddle.net/Freewind/PmsFQ/

like image 753
Freewind Avatar asked May 06 '12 01:05

Freewind


People also ask

What does $( function ()) short hand do?

It's just shorthand for $(document). ready() , as in: $(document). ready(function() { YOUR_CODE_HERE }); Sometimes you have to use it because your function is running before the DOM finishes loading.

What will $( Div do?

It means "create a jQuery-wrapped div element on the fly". When the parameter has a single tag, such as $('<div />') or $('<a></a>') , jQuery creates the element using the native JavaScript createElement() function. Note that $('<div>') would work the same way. In HTML, <div/> never creates empty div element.

What does $() mean in JavaScript?

The $() function The dollar function, $(), can be used as shorthand for the getElementById function. To refer to an element in the Document Object Model (DOM) of an HTML page, the usual function identifying an element is: document.

What does the $() mean in jQuery?

In jQuery, the $ sign is just an alias to jQuery() , then an alias for a function. This page reports: Basic syntax is: $(selector).action() A dollar sign to define jQuery. A (selector) to "query (or find)" HTML elements.


2 Answers

Because the direct children of a <table> can only be <thead>, <tbody>, or <tfoot> (or <colgroup> or <caption>, but those don't contain rows).

The browser's DOM will implicitly wrap stray <tr>s in a <tbody>. (for browsers that don't do this, jQuery fakes it instead)

You need to write $('#table > tbody > tr').

like image 197
SLaks Avatar answered Sep 24 '22 21:09

SLaks


This is because browsers automatically insert the <tbody> element between your <table> and <tr>, such that the rows are no longer the direct children of your table.

like image 41
Hubro Avatar answered Sep 22 '22 21:09

Hubro