views:

30

answers:

3

Quick question, is a jQuery child selector without a parent ever valid? If so, how would you use it?

Example of the jQuery child selector:

$('ul > li')

Example of jQuery child selector without parent:

$('> li')

The second example above doesn't work. However I can't remember if I saw it in the past before or I've seen something advance like:

$('ul').not('>li')

Doesn't really work either (but doesn't pop up an error message, so it's just ignored?)

So my question is would you EVER use a child selector without a parent, and have it be a valid jQuery selector.

Thanks, sorry if question is dumb. :)


Edit:

Along with Nick's jQuery.find example on the bottom, another use case is

$('ul:has(>li)')

Note: that $('ul').has('>li') is wrong and should be written

$('ul').has('ul>li')

AND for not()

Not sure if I have it correct, but you wouldn't ever use a > inside of not() directy because not() only concern about one element, while > compares multiple elements. However you can do something like

$('li:not(:has(>p))'
A: 

I cannot think of a situation that requires a child selector without a parent. The child selector is used to select immediate children of a parent element. If there is no parent element, whose children should be selected?

elusive
A: 

Why would you ever want that ?

You could always use $('* > li') although i can't really see what that would accomplish, as li should always be a child of something ul or ol

Gaby
+3  A: 

Yes it works without a parent, but it can't be on the default context, because your <li> isn't a direct child of a document. Also, it wouldn't make any sense by itself really, since it's a direct child of something, it'd be the same as $("li").

When would it be used? possibly to cut down on code, for example:

$(this).find("> li > span a");
//as opposed to not being able to start with it:
$(this).children("li").children("span").find("a");
Nick Craver
+1! Nice explanation! You've got a small typo in your code: `$(this).childred("li")` should be `$(this).children("li")`.
elusive
@elusive - thanks for the catch :) fixed!
Nick Craver
Quang
@Quang - In some cases yes, others, no, the `>` and `:has()` don't get along so nicely, it's a bug in sizzle with the way the selector parts are popped, I need to put in a bug report on that one.
Nick Craver
Sorry I'm still trying to wrap my head around what a '>' with no parent does. In your example what the difference between $(this).find("> li > span a") AND $(this).find("li > span a") ? First one direct child, second one all descendants?
Quang
@Quang - The first will only find a `<li>` that's an *immediate* child of `this`, the second will start with a `<li>` anywhere beneath.
Nick Craver
Thanks Nick, I got it. Keep forgetting how > works, always confuse it with :first / :first-child
Quang