问题描述
最近,我开始学习HTML和JS.当我使用 document.querySelectorAll()
API时,我看到它可以使用
Recently I am starting to learn HTML and JS. When I am leaning the document.querySelectorAll()
API, I saw it can use
document.querySelectorAll('#example-container li:first-child');
选择ID名称为example-container的列表的第一个子代.
to select the first child of the list which has id name is example-container.
所以我想可能是
document.querySelectorAll('#example-container li:second-child');
可以选择ID名称为example-container的列表的第二个子项.
can select the second child of the list which has id name is example-container.
但是显然这是错误的.所以我很困惑如何使用 querySelectorAll()
访问列表的第二或第三项?
But obviously it is wrong. So I am confused how can I access the second or third item of the list by using querySelectorAll()
?
我在下面发布了HTML代码:
I post the HTML code below:
<div id="example-container">
<ul>
<li class="feature">Luxurious sized master suite</li>
<li class="feature">Oversized walk-in closet</li>
<li class="feature">Frameless Beech cabinetry with concealed hinges</li>
<li class="feature">Elegant slab white quartz countertops with large backsplash</li>
<li class="feature">Dual china sinks with Moen faucets</li>
<li class="feature">Clear frameless shower enclosures</li>
</ul>
推荐答案
由于您要问如何使用查询选择器选择第二个或第三个元素,如 document.querySelectorAll('#example-container li:second-child')
,我将告诉您如何使用CSS选择器和 document.querySelectorAll()
来选择它们.
Since you are asking what you can do to select the second or third element using query selectors, like document.querySelectorAll('#example-container li:second-child')
, I am going to tell you how to select them with both css selectors and document.querySelectorAll()
.
您可以使用:
const el = document.querySelectorAll('#example-container li')[1];
选择列表中的第二个元素.这可能是用JavaScript的首选方式.
to select the second element in the list. And this is probably the preferred way to do it in JavaScript.
但是css有一个叫做:nth-child()
的东西,它允许您在列表中选择一个特定的孩子.在JS中,您可以执行以下操作:
But css has something called :nth-child()
which allows you to choose a specific child in the list. In JS you could do something like:
const el = document.querySelector('#example-container li:nth-child(2)');
选择第二个列表项.请注意,您不需要 querySelectorAll()
方法.
to select the second list item. Notice that you do not need the querySelectorAll()
method.
我希望能有所帮助.
这篇关于使用querySelectorAll()选择列表的第二个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!