You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用JS DOM方法选中第二个class为box的元素并存储到变量

问题相关HTML代码
<div class="box">
    First collection
</div>

<div class="box">
    Second collection
</div>
实现方法

共有两种常用的实现方案:

  • 方案1:使用document.getElementsByClassName
    document.getElementsByClassName会返回所有匹配类名的元素组成的动态类数组集合,元素顺序和DOM树中的排列顺序一致,索引从0开始计数,第二个符合条件的元素对应索引值1。
    代码示例:
const secondBox = document.getElementsByClassName('box')[1];
  • 方案2:使用选择器API
    document.querySelector仅会返回第一个匹配选择规则的元素,你可以替换为document.querySelectorAll获取所有匹配元素的静态集合,再按索引取值:
const secondBox = document.querySelectorAll('.box')[1];

你也可以直接通过CSS伪类选择器精准定位第二个元素,不需要手动读取索引:

const secondBox = document.querySelector('.box:nth-of-type(2)');

可以通过输出内容验证是否选中正确元素:

console.log(secondBox.textContent); // 输出 "Second collection"

内容的提问来源于stack exchange,提问作者huy8856

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.20 16:15:11