简体   繁体   中英

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

 // 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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