【问题标题】:How to select child elements under id in jQuery如何在jQuery中选择id下的子元素
【发布时间】:2012-08-02 21:54:40
【问题描述】:

示例代码:

<div id='container'>
  <h1>heading 1</h1>
  <h2>heading 2</h2>
  <p>paragraph</p>
</div>

我想要一个与此 CSS 选择器等效的 jQuery 来选择 div 下的 h1 元素:

#container h1 {}

【问题讨论】:

    标签: jquery css-selectors


    【解决方案1】:

    您可以简单地实现完全相同的选择器

    $('#container h1')
    

    选择在#container 元素中找到的每个h1 元素,或者:

    $('#container > h1')
    

    仅选择那些将 #container 元素作为其父元素(不是祖父母或其他形式的祖先)的 h1 元素。

    或者,如果您愿意:

    $('#container').find('h1')
    

    您也可以将其限制为特定的h1 元素:

    $('#container h1:first')
    

    仅选择#container 元素中的第一个 h1 元素。

    参考资料:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-17
      • 2010-10-19
      • 2015-07-29
      • 1970-01-01
      • 2015-10-26
      • 2015-04-01
      相关资源
      最近更新 更多