> jQuery Child Selector without a parent allowed?

落爺英雄遲暮 提交于 2019-12-11 07:25:45

问题


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

回答1:


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



回答2:


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?




回答3:


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



来源:https://stackoverflow.com/questions/3992473/jquery-child-selector-without-a-parent-allowed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!