Is this a bug in how jQuery treats child selectors?
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.
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"
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.
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.
精彩评论