What is the difference between jQuery's space and > selectors?

牧云@^-^@ 提交于 2019-12-20 19:10:36

问题


What's the difference between the space and > selectors? And possibly related, how can I look for something that's the direct child of something else, and not lower down the descendant line?


回答1:


For:

<ul>
  <li>Item 1</li>
  <li>Item 2
    <ul>
      <li>Item 2.1</li>
      <li>Item 2.2</li>
    </ul>
  </li>
  <li>Item 3</li>
</ul>

For example

$("ul > li").addClass("blah");

adds class "blah" to 1 2 and 3 whereas:

$("ul li").addClass("blah");

add class "blah" to every list element.

I'm not sure what you're referring to with < and ? operators.




回答2:


In CSS, > means "direct child of": only nodes that are direct children are selected.

While a space means "any descendant of": direct children and children of those children could be selected.

I would wager jQuery uses the same convention.




回答3:


As already mentioned, a space will select any descendant, whereas > will select only immediate children. If you want to select only grandchildren or great-grandchildren, then you could use this:

#foo > * > * > .bar

(all elements with class "bar" which are great grandchildren of the element with id "foo")




回答4:


look at this..

$(".testit > a") //match the first <a> tag below
$(".testit a") // matches all <a> tag below

<p class="testit">
  <a href="#">All the rules will match this</a>
  <span>
    <a href="#">second rule can only select this</a>
  </span>
</p>


来源:https://stackoverflow.com/questions/1218068/what-is-the-difference-between-jquerys-space-and-selectors

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