Is there any difference between $("#item1 #item2") and $("#item1>#item2")?
I was reviewing code and found that
$("#item1 #item2") and $("#item1>#item2")
are used interchangeably. Is there any difference or is it one and the sa开发者_JS百科me?
Both will match
<div id="item1">
<div id="item2">
</div>
</div>
But only the first one will match
<div id="item1">
<div>
<div id="item2">
</div>
</div>
</div>
The first expression uses the descendant selector. The >
symbol in the second expression is the child selector. Both are standard CSS selectors.
However, since id
s must be unique, both are overcomplicated. Instead, you should just use $('#item2')
The same as the CSS selectors
#this #that
means any #that
that is a child of #this
.
Where as
#this>#that
Means only #that
which is a direct descendant of #this
.
More reading on descendant selectors.
The >
sign means "include only elements that are direct children of that element". So if you want to select only the children being subnodes of #item1
, use it, otherwise use first option.
>
means the immediate, direct child.
Direct
<div id="a">
<div id="b">
</div>
</div>
Indirect
<div id="a">
<div>
<div id="b">
</div>
</div>
</div>
See the documentation: http://api.jquery.com/child-selector/
精彩评论