0

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.

KooiInc
  • 119,216
  • 31
  • 141
  • 177
  • We need more context here to be able to answer the question. Please provide a [minimal reproducable example](https://stackoverflow.com/help/minimal-reproducible-example). – KooiInc Apr 02 '21 at 07:02

3 Answers3

0

You can try like this:

var modal = document.querySelectorAll(".myModal");  //one time
modal[0] //first element
modal[1] //second element
0
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.

Toxy
  • 696
  • 5
  • 9
0

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>
Mara Black
  • 1,666
  • 18
  • 23