Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 596
Anurag Avatar asked Jan 16 '10 02:01

Anurag


People also ask

How do jQuery selectors work?

jQuery selectors allow you to select and manipulate HTML element(s). jQuery selectors are used to "find" (or select) HTML elements based on their name, id, classes, types, attributes, values of attributes and much more. It's based on the existing CSS Selectors, and in addition, it has some own custom selectors.

Are jQuery selectors the same as CSS selectors?

In jQuery, the class and ID selectors are the same as in CSS. If you want to select elements with a certain class, use a dot ( . ) and the class name. If you want to select elements with a certain ID, use the hash symbol ( # ) and the ID name.

What is a child selector?

Child Selector: Child Selector is used to match all the elements which are children of a specified element. It gives the relation between two elements. The element > element selector selects those elements which are the children of the specific parent.


1 Answers

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"
like image 178
Doug Neiner Avatar answered Nov 01 '22 23:11

Doug Neiner