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')
- Matches all elements with tag name tr that are descendents of table.
- Matches all elements with tag name tr that are direct children of table.
- 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)
精彩评论