What is the difference direct descendent (>) vs. descendant in jQuery selectors?

南楼画角 提交于 2020-01-30 20:13:04

问题


What's the difference between these two jQuery statements? They seem to do the same thing by getting all the children div tags.

$("#mainblock div")
$("#mainblock > div")

回答1:


$("#mainblock > div") = the childs only level

$("#mainblock div") = all the childs+ desendents.




回答2:


Have a look at jQuery Selectors

Child Selector ("parent > child") - Hierarchy Selects all direct child elements specified by "child" of elements specified by "parent".

Descendant Selector ("ancestor descendant")- Hierarchy Selects all elements that are descendants of a given ancestor.




回答3:


$("#mainblock div")

This one target all DIVs inside "#mainblock" not matter it's direct child of "#mainblock", or child of child of main block or so on.

$("#mainblock > div")

This will target only direct child DIVs of "#mainblock" and ignore other DIVs. This one is faster then above in case you have only direct childs. Because it's not try to find inside other elements of childs.




回答4:


The first one will get all divs descendant of #mainblock. The second one will get all divs that are immediate children of #mainblock




回答5:


$("#mainblock div")

Matches any div element that is a descendant of #mainblock.

$("#mainblock > div")

Matches any div element that is a child of #mainblock .

check http://www.w3.org/TR/CSS2/selector.html




回答6:


The first one will select any div that is a child of `#mainblock' at any level. The second will select any div that is an immediate child.

See this link for more info on the CSS > selector which behaves the same as in jQuery.




回答7:


$("#mainblock div") find all the divs under #mainblock

$("#mainblock > div") only found its child

suppose you have below HTML structure:

    <div id="mainblock"> 
      <div>
        <div></div> 
        <div></div>
      </div>
     <div></div>
     <div></div>
   </div>

Then

$("#mainblock div").length = 5
$("#mainblock > div").length = 3


来源:https://stackoverflow.com/questions/10223143/what-is-the-difference-direct-descendent-vs-descendant-in-jquery-selectors

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