Reputation: 1087
Sometime I faced this problem, why not map loop working, I still did not get solution.
let slide = document.querySelectorAll('.slide');
//not working below
slide.map((s)=> s.onmousedown = slideFunction);
function slideFunction(){
alert('HI')
}
// working below
let num = [3,2,5,2];
num.map((n)=> alert(num));
the map loop not working each slide but num value array working.
Upvotes: 0
Views: 75
Reputation: 97130
A couple of issues:
map()
for this, but forEach()
.document.querySelectorAll()
function returns a NodeList
, not an array. You need to convert it to an array to call array functions like map()
on it.NodeList
does provide a forEach()
function, so you can invoke that directly on the result of document.querySelectorAll()
.let slides = document.querySelectorAll('.slide');
slides.forEach((s) => s.onmousedown = slideFunction);
function slideFunction() {
alert('Hi')
}
<div class="slide">Slide one</div>
<div class="slide">Slide two</div>
It's probably also cleaner to attach an event handler instead of directly assigning the event handler.
Upvotes: 2