简体   繁体   English

DOM 获取元素方法

[英]DOM get element methods

<div class="box">
    First collection
</div>

<div class="box">
    Second collection
</div>

Hi, I'm still studying the JS, I have this exercise that requires me to select the second 'box' class and store it into a variable, I just don't know how to do it, can someone help me, thank you.嗨,我还在学习 JS,我有这个练习需要我 select 第二个“盒子” class 并将其存储到变量中,我只是不知道该怎么做,有人可以帮我吗,谢谢.

I have tried using document.GetElementsByClassName and document.querySelector but I just don't know how to pick the second one and store it to a variable.我曾尝试使用document.GetElementsByClassNamedocument.querySelector但我只是不知道如何选择第二个并将其存储到变量中。

Both can be used:两者都可以使用:

.getElementsByClassName('box')[1]

 var selected = document.getElementsByClassName("box")[1]; console.log(selected);
 <div class="box"> First collection </div> <div class="box"> Second collection </div>

.querySelector('.box:nth-of-type(2)')

 var selected = document.querySelector('.box:nth-of-type(2)'); console.log(selected);
 <div class="box"> First collection </div> <div class="box"> Second collection </div>

you can do it by using .getElementByClassName then it should return a list of item with the class name box in Array, then you can just simply select which boxes you want.你可以通过使用.getElementByClassName来做到这一点,然后它应该返回一个带有 class 名称框的项目列表,然后你可以简单地 select 你想要的框。

const boxes =  document.getElementsByClassName("box")

boxes[0]
boxes[1]
boxes[boxes.length]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM