What is the difference direct descendent (>) vs. d

2019-03-12 15:49发布

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

7条回答
乱世女痞
2楼-- · 2019-03-12 16:04

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

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

查看更多
Summer. ? 凉城
3楼-- · 2019-03-12 16:14
$("#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

查看更多
Viruses.
4楼-- · 2019-03-12 16:18

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

查看更多
不美不萌又怎样
5楼-- · 2019-03-12 16:20
$("#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.

查看更多
爷、活的狠高调
6楼-- · 2019-03-12 16:23

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.

查看更多
看我几分像从前
7楼-- · 2019-03-12 16:23

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.

查看更多
登录 后发表回答