开发者

What's the difference between these two jQuery selectors?

开发者 https://www.devze.com 2022-12-10 19:21 出处:网络
With this markup: &l开发者_JAVA百科t;div id=\"e\"> <div id=\"f\"></div> </div>

With this markup:

&l开发者_JAVA百科t;div id="e">  
    <div id="f"></div>  
</div>

Does $('#e > #f') return the same as $('#e #f')?


The parent > child selector will only look for direct child elements, while the ancestor descendant will look for any descendant element.

For example, with the following markup:

<div class="foo">
  <div>
    <div class="bar"></div>
  </div>
</div>

$('.foo > .bar') will not find the .bar element, while $('.foo .bar') does find it because .foo isn't direct child from .bar, but it is a descendant.


First, I'm assuming you meant $('#e > #f') and $('#e #f').

In your example, they will both return the same thing. The difference is that $('#e #f') would also return a div in this case:

<div id="e">
  <div id="g">
    <div id="f"></div>
  </div>
</div>

$('#e > #f'), on the other hand, would return nothing there, as it only selects elements which are direct children of other elements.


That will not work, because you don't specify what elements you are looking for. You need to put #e > #f or #e #f to grab by your IDs.

If this were a real scenario, #e > #f will only find children, nothing nested below that. #e #f will grab any id="f" elements, no matter how far nested they may be inside your structure.


In this example, yes they will return the same thing.


Yes, as there are no e or f elements in HTML, they will always return empty jQuery objects.

The call $('#e > #f') will return the element with id="f" if it's a direct decendant of the element with id="e".

The call $('#e #f') will return the element with id=f if it's somewhere inside the element with id="e".

Edit:
Note: As the question was edited after I answered, the first sentence does not apply to what the question currently looks like.

0

精彩评论

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

关注公众号