Search code examples
jquerysyntaxselectorparent

> jQuery Child Selector without a parent allowed?


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))'

Solution

  • 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");