示例代码:
<div id='container'>
<h1>heading 1</h1>
<h2>heading 2</h2>
<p>paragraph</p>
</div>
我想要一个与此 CSS 选择器等效的 jQuery 来选择 div
下的 h1
元素:
#container h1 {}
最佳答案
您可以简单地实现完全相同的选择器:
$('#container h1')
选择 #container
元素中找到的每个 h1
元素,或者:
$('#container > h1')
它仅选择那些将 #container
元素作为父元素的 h1
元素(不是祖 parent ,或其他形式的祖先)。
或者,如果您愿意的话:
$('#container').find('h1')
您还可以将其限制为特定的 h1
元素:
$('#container h1:first')
仅选择 #container
元素中的第一个 h1
元素。
引用文献:
关于jquery - jQuery如何选择id下的子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11819622/