8

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/

Freewind
  • 193,756
  • 157
  • 432
  • 708
  • Please go the the *other* question and close it for this one if warranted (this question is written better and more to the point). –  May 06 '12 at 07:15
  • @pst: Done. It always makes me a little uneasy knowing the close description says "this is the same as *earlier* questions", but I think it's alright in this case. – BoltClock May 06 '12 at 07:23

3 Answers3

14

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').

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • The second sentence is true for HTML (as well as HTML5), but not XHTML. See [these](http://stackoverflow.com/a/5568877/106224) two [answers](http://stackoverflow.com/a/7491956/106224). – BoltClock May 06 '12 at 07:33
3

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.

Hubro
  • 56,214
  • 69
  • 228
  • 381
2

Your browser is adding a tbody element so tr is not the child of the table.

  • They will still be direct descendants of the table... Just not the children of it :-) – Hubro May 06 '12 at 01:59
  • @Codemonkey That's what I meant by "_direct_ descendant." But yeah, child is better. –  May 06 '12 at 02:00
  • @Codemonkey: ["direct descendant" is the same as "child"...](http://stackoverflow.com/a/3225905/106224) – BoltClock May 06 '12 at 05:56
  • @BoltClock Perhaps in programming, but in all the references I could find "direct descendant" just means following a straight path of lineage, e.g. I'm a direct descendant of my grandfather – Hubro May 06 '12 at 13:06