NIKHIL CHANDRA ROY
NIKHIL CHANDRA ROY

Reputation: 1087

How to solve Javascript map loop not working each div tag?

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

Answers (2)

Robby Cornelissen
Robby Cornelissen

Reputation: 97130

A couple of issues:

  • You should not be using map() for this, but forEach().
  • The 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.
    However, 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

sney2002
sney2002

Reputation: 896

It is because querySelectorAll returns a NodeList, it is an array-like object (it seems like an array but it is not).

You should convert it to an array:

Array.from(slide).map((s)=>  s.onmousedown = slideFunction);

Upvotes: 1

Related Questions