Why doesn't the $ ('# table> tr') selector match? (always return 0)

Html code:

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

Js code with jquery:

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

Result:

  0,1 

Why #table > tr first #table > tr get 0?

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

+7
jquery jquery-selectors
May 6 '12 at 1:54 AM
source share
3 answers

Since the direct children of <table> can be <thead> , <tbody> or <tfoot> (or <colgroup> or <caption> , but do not contain strings).

In the DOM browser, the tray <tr> in the <tbody> will implicitly wrap around. (for browsers that don't, jQuery fakes it)

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

+13
May 6 '12 at 1:56 AM
source share

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

+3
May 6 '12 at 1:57
source share

Your browser adds a tbody element, so tr not a child of the table.

+2
May 6 '12 at 1:57
source share



All Articles