简体   繁体   English

如何通过 class 获取数组中的多个元素?

[英]How to get multiple elements in array by class?

I am trying to get multiple elements using an array.我正在尝试使用数组获取多个元素。 I'm bad at describing, so I'll try and show.我不擅长描述,所以我会尝试展示。

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

Any help is appreciated.任何帮助表示赞赏。 Thank you.谢谢你。

You can try like this:你可以这样尝试:

var modal = document.querySelectorAll(".myModal");  //one time
modal[0] //first element
modal[1] //second element
var parent = document.querySelectorAll('.myModal');
Array.prototype.slice.call(parent).forEach(function(child){ 

// your code 

});

Hope you are looking for this as your question doesn't give any idea what you want exactly.希望你正在寻找这个,因为你的问题并没有给出你到底想要什么的任何想法。

You can this is several ways, you can read more about how to iterate through it at Accessing the matches您可以通过几种方式,您可以在访问匹配项中阅读有关如何迭代它的更多信息

Note that you cannot have the same variable twice, in your code rename the second one and it will work: Declaring two variable with the same name请注意,您不能两次拥有相同的变量,在您的代码中重命名第二个变量,它将起作用: 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>

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

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