开发者

jQuery - Different selectors for descendants?

Can someone please explain how the selectors work for the different descendants? I've looked a bit online but t开发者_运维百科he 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. 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.


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


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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜