views:

120

answers:

3

Is there a bug in how jQuery handles child selectors or am I missing out on something obvious? I can't get it to work when the child is anything other than *.

Here's the jQuery selector I am running:

$("#myTable > tr").each(function() {
    // do somthing }
);

And the table structure is:

<table id="myTable">
    <tr>
        <td><button>someButton</button></td>
        <td><textarea>...</textarea></td>
    </tr>
</table>

No elements are matched with the above selector #myTable > tr. But the two selectors listed below work fine.

$("#myTable tr") // search all descendants for tr

or use a wildcard to match children:

$("#myTable > *") // search all child elements

Any ideas on what could be wrong here?

Thanks for the rapid answers guys! Unfortunately can only select one.

+10  A: 

Its because Firefox automatically adds tbody elements around your tr elements if none are supplied. You really can't use table > tr.

You have:

<table id="myTable">
    <tr>
        <td><button>someButton</button></td>
        <td><textarea>...</textarea></td>
    </tr>
</table>

But Firefox sees this:

<table id="myTable">
  <tbody>
    <tr>
        <td><button>someButton</button></td>
        <td><textarea>...</textarea></td>
    </tr>
  </tbody>
</table>

Other elements will work just fine:

<div>
  <strong>Hi</strong>
</div>

And the selector:

alert( $("div > strong").text() ); // Alerts "Hi"
Doug Neiner
+5  A: 

There is an implicit <tbody> element added meaning instead of:

<table id="myTable">
  <tr>
    <td><button>someButton</button></td>
    <td><textarea>...</textarea></td>
  </tr>
</table>

the DOM actually contains:

<table id="myTable">
<tbody>
  <tr>
    <td><button>someButton</button></td>
    <td><textarea>...</textarea></td>
  </tr>
</tbody>
</table>

so change it to:

$("#mytable > tbody > tr");

Using <tbody>, <thead> and <tfoot> elements in your tables is a good habit to get into.

cletus
+1  A: 

yep, Doug's completely right. Just to complement his answer, maybe you are aware, or perhaps not, but remember that jQuery traverses the DOM, and not the HTML "text" that you send to the browser.

The DOM is the browser's interpretation on the HTML you send it.

andy
Thanks Andy. I wasn't aware that browsers add the `tbody` element implicitly. Actually I always use the DOM Inspector while debugging such errors, and the `tbody` element was indded right there all this time, but somehow I didn't see it :)
Anurag