jQuery - Different selectors for descendants?

204 views Asked by At

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')
3

There are 3 answers

1
Orson On BEST ANSWER
  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.
0
antpaw On

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

1
user229044 On

You can't have looked terribly hard, jQuery's documentation is pretty clear on the subject.

Given some simple markup,

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

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

This is how selects will work:

  • $("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)