简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM