views:

79

answers:

3

Can someone please explain how the selectors work for the different descendants? I've looked a bit online but the descriptions I've found so far don't seem to be terribly different.

For example, what's the difference between these three?

$('table tr')
$('table > tr')
$('table + tr')
+1  A: 
  1. Matches all elements with tag name tr that are descendents of table.
  2. Matches all elements with tag name tr that are direct children of table.
  3. Matches all elements tr immediately preceded by sibling table.
Colour Blend
Thanks. That makes a lot more sense now as to why it's working the way it is.
Sonny Boy
You are welcome Sonny Boy.
Colour Blend
A: 

table tr is a bad example for this because you cant have a tr without table, and the also don't need the jquery function

p span

this one selects all the span tags inside the p tag

p > span

this one selects only the first nested span tag inside the p

p + span

selects only that span tag, that comes right after the p in your markup

antpaw
A: 

You can't have looked terribly hard, jQuery's documentation is pretty clear on the subject: http://docs.jquery.com/Selectors

<div>
  <span id="A"></span>
  <p><br /><span id="B"></span></p>

  <form>
    <span id="C"></span>
    <span id="D"></span>
  </form>
</div>

basically:

$("div span") matches any span within a div, however far nested with a div they might be (A,B,C,D)

$("div > span") matches spans which are immediate descendts of divs (A)

$("br + span") matches span next to a br (B)

$("form span") matches spans within a form (C, D)

$("form span:first") matches only the first span with a form (C)

meagar