开发者

What's the difference between $('x > y'), $('y', 'x'), and $('x y')?

The three jQuery selectors below all have the same result. What is the difference?

<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <p><span>Hello</span>, how are you?</p>开发者_开发百科;
<p>Me? I'm <span>good</span>.</p>
<script>
  $('p > span').css('color','red');
OR
  $('span', 'p').css('color','red');
OR
  $('p span').css('color','red');
</script>

</body>
</html>


$('span', 'p') and $('p span') are identical, both will select any span elements that are descendants of any p element no matter the depth.

$('p > span') on the other hand will select span elements that are direct children of the p element. So for example this selector would not select the span element in the following example:

<p>
    <a href="#">
        <span>Test</span>
    </a>
</p>

..whereas the other two would select it just fine.


The difference is that p > span only matches if the span is a direct decendant of the paragraph.

Given this markup:

<p><div><span>Hello</span>, how are you?</div></p>
<p>Me? I'm <span>good</span>.</p>

the selector p > span would only match the span in the second paragraph.


First is child-selector

Second is multiple-selector

Third is descendant-selector

All links are to the jquery API

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜