【问题标题】:How to get multiple elements in array by class?如何按类获取数组中的多个元素?
【发布时间】:2021-04-02 06:52:02
【问题描述】:
我正在尝试使用数组获取多个元素。我不擅长描述,所以我会尝试展示。
var modal = document.querySelectorAll(".myModal")[0]; // <-- gets the first element in an array
var modal = document.querySelectorAll(".myModal")[1]; // <-- gets the second element in an array; doesn't work
感谢任何帮助。谢谢。
【问题讨论】:
标签:
javascript
css
arrays
get
element
【解决方案1】:
你可以这样试试:
var modal = document.querySelectorAll(".myModal"); //one time
modal[0] //first element
modal[1] //second element
【解决方案2】:
var parent = document.querySelectorAll('.myModal');
Array.prototype.slice.call(parent).forEach(function(child){
// your code
});
希望您正在寻找这个,因为您的问题并没有给出您确切想要什么的任何想法。
【解决方案3】:
你可以通过几种方式,你可以在Accessing the matches阅读更多关于如何迭代它的信息
请注意,您不能两次使用相同的变量,在您的代码中重命名第二个变量,它将起作用:Declaring two variable with the same name
// one way
let modal0 = document.querySelectorAll(".myModal")[0];
let modal1 = document.querySelectorAll(".myModal")[1];
console.log("one way")
console.log(modal0)
console.log(modal1)
//another way
const modalElemenet = document.querySelectorAll(".myModal");
let firstElement = modalElemenet[0];
let secondElement = modalElemenet[1];
console.log("second way")
console.log(firstElement);
console.log(secondElement);
// take all childrens
const modal = document.querySelectorAll(".myModal");
console.log("take all")
modal.forEach(e => console.log(e));
<div class="myModal"> 1 </div>
<div class="myModal"> 2 </div>
<div class="myModal"> 3 </div>