[英]How to get multiple elements in array by class?
我正在嘗試使用數組獲取多個元素。 我不擅長描述,所以我會嘗試展示。
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
任何幫助表示贊賞。 謝謝你。
你可以這樣嘗試:
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
});
希望你正在尋找這個,因為你的問題並沒有給出你到底想要什么的任何想法。
您可以通過幾種方式,您可以在訪問匹配項中閱讀有關如何迭代它的更多信息
請注意,您不能兩次擁有相同的變量,在您的代碼中重命名第二個變量,它將起作用: 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.