Alexsander Akers
Alexsander Akers

Reputation: 16024

What's the difference between these two jQuery selectors?

With this markup:

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

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

Upvotes: 0

Views: 226

Answers (5)

Christian C. Salvad&#243;
Christian C. Salvad&#243;

Reputation: 827256

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.

Upvotes: 8

Guffa
Guffa

Reputation: 700222

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.

Upvotes: 0

igul222
igul222

Reputation: 8637

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.

Upvotes: 3

Nick Jurista
Nick Jurista

Reputation: 1434

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.

Upvotes: 1

Robert Deml
Robert Deml

Reputation: 12532

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

Upvotes: 0

Related Questions