Manuel
Manuel

Reputation: 4228

jQuery selectors: is the order of selectors important?

I've an html document which looks like this:

<div id="panel_comments">
  <table id="panel_comments_table">
    <tr>
      <td style="width: 150px;">Monday: </td>
      <td><textarea id="panel_comments_monday" rows="4" cols="60" >Monday comment area</textarea></td>
    </tr>
    .. same with the other 6 weekdays
  </table>
</div>

Now, if I want to select all textareas I would do the following, which is in a natural language: give me all elements which are textareas, with the following ids:

$("textarea [id^=panel_comments_]")

but it gives me an empty result. Instead I have to rearrange the selectors like this, which is in a natural language give me all elements with the ids, and which are textareas:

$("[id^=panel_comments_] textarea")

Why does the ordering of the selectors matter?

Upvotes: 1

Views: 178

Answers (3)

A. Wolff
A. Wolff

Reputation: 74420

You want this, no extra space:

$("textarea[id^=panel_comments_]")

Using space as: $("textarea [id^=panel_comments_]") means select all elements with IDs inside textarea.

Using: $("[id^=panel_comments_] textarea") means select all textarea inside elements with ID starting with your selector string.

Following BoltClock's comment, type selector must be used before any extra filter selector, which means:

  • $("textarea[id^=panel_comments_]") is valid
  • $("[id^=panel_comments_]textarea") is not valid

Upvotes: 3

Felix Kling
Felix Kling

Reputation: 816322

The space is significant here, it is the descendant selector. Just omit it:

textarea[id^=panel_comments_]

The reason why [id^=panel_comments_] textarea seems to work is that it selects the div element with ID panel_comments and then finds all textareas that are descendants of it. So, this only works "by accident" since the div and the textarea have similar IDs. Had you given the div element a completely different ID, it would not have worked.


CSS selectors work on hierarchical structures, like HTML, so it is only reasonable that the order of "sub-selectors" matters.

Only if you don't want to express relations between elements, the order almost doesn't matter:

A simple selector is either a type selector or universal selector followed immediately by zero or more attribute selectors, ID selectors, or pseudo-classes, in any order.

Upvotes: 3

Adil Shaikh
Adil Shaikh

Reputation: 44740

$("textarea[id^=panel_comments_]")

remove that extra space

Upvotes: 1

Related Questions