Home > database >  Javascript forEach is not a function
Javascript forEach is not a function

Time:08-18

I'm trying to add a click event to all my edit icons. Each icon has an ID that I'm using to call them.

<div><img src="" id="editCatsSVG" /></div>

Here's my js file below.

const edicatsIcon = document.querySelector('#editCatsSVG'),
      deleteCatsIcon = document.querySelector('#deleteCatsSVG');
      
const catsActionsModal = document.querySelector('#catsActions'),
      closeCatsModal = document.querySelector("#closeModalIConButton");




edicatsIcon.forEach(addEventListener("click", function(){
    catsActionsModal.style.display = "flex";
}));

closeCatsModal.addEventListener("click", function(){
    catsActionsModal.style.display = "none";
    
});

Is there a way I can add the forEach func so when all the editcatsIcon is clicked, the modal shows?

please?

Many thanks.

CodePudding user response:

document.querySelector returns an Element or null - neither of which have forEach as a method (see querySelctor on MDN).

Just repeat what you are doing for closeCatsModal:

edicatsIcon.addEventListener("click", function(){
    catsActionsModal.style.display = "flex";
})

CodePudding user response:

You might want to use querySelectorAll instead of querySelector, and also check if the element exists before running a forEach on it, like this:

const arr = document.querySelectorAll(".class" || "#id");

arr && arr.forEach(function () { ... })

CodePudding user response:

const edicatsIcon = document.querySelector('#editCatsSVG') will return one element, not an array of elements. Also, you're querying for elements with the id editCatsSVG, and you can't have duplicate ids.

This

edicatsIcon.forEach(addEventListener("click", function(){
    catsActionsModal.style.display = "flex";
}));

Should be

edicatsIcon.addEventListener("click", function(){
    catsActionsModal.style.display = "flex";
});

CodePudding user response:

In addition to the earlier answer. Element.querySelector() return a single element (which is not iterable with .forEach). Element.querySelectorAll() returns a NodeList iterable (array like) which in modern browsers supports .forEach().

If you want to select a single element, use Element.querySelector(), if you want to select multiple, use Element.querySelectorAll().

CodePudding user response:

Thanks for all the contributions, what I did was simple.

I added a querySelectorAll to the icons below

const edicatsIcon = document.querySelectorAll('#editCatsSVG'),

Then I checked if any of the elements has a click event, if true, I called my function below


      function openModal() {
        catsActionsModal.style.display = "flex";
    }```

and I got what I needed. Thanks all.
  • Related