views:

136

answers:

5

With this markup:

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

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

+9  A: 

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.

CMS
...this is invalid HTML. selectors won't find much of anything...
Jason
@Jason: added the missing `</div>` closing tag...
CMS
A: 

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

Robert
+1  A: 

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.

wambotron
+3  A: 

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.

igul222
Your assumption is correct, as that is verbatim to what I posted originally. Thank you for your answer.
Alexsander Akers
Ah, sorry- I'm not sure why, I thought you had posted `$('e > f')`. I must have misread.
igul222
A: 

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.

Guffa
Read the first part under 'With this markup:'; then rephrase your first sentence.
Alexsander Akers
@Alexsander: I see, you changed your question after I wrote the answer...
Guffa