简体   繁体   中英

can't add event listeners to elements using querySelectorAll()

I'm trying to add a mouseover event on some links with the data-hide-links attribute, but it's not working at all.

I know that my loop is working fine and that it selects the right elements because I can console.log() the elements that I want. I also know for sure that the event listener is not adding to the element because when I look at the prototype of the elements the onmouseover property is null

Here's the code:

 let hideLinks = document.querySelectorAll("[data-hide-cursor]"); for (let i = 0; i < hideLinks.length; i++) { hideLinks[i].addEventListener("mouseover", () => { document.getElementById("cursor").classList.add("hide"); }); }
 #cursor { top: 0; left: 0; border-radius: 50%; pointer-events: none; z-index: 1000; } #cursor>div { border-radius: 50%; width: 1.25rem; height: 1.25rem; background: black; transition: transform 0.5s ease, opacity 0.35s ease; }
 <div id="cursor" data-cursor> <div></div> </div> <button data-hide-cursor type="submit" class="submit-mail"> Submit </button>

I tried to deconstruct the elements into an array using let [...hideLinks] =... but it did not change a thing.

Your code works fine. Class hide just doesn't do anything

 let hideLinks = document.querySelectorAll("[data-hide-cursor]"); for (let i = 0; i < hideLinks.length; i++) { hideLinks[i].addEventListener("mouseover", () => { document.getElementById("cursor").classList.add("hide"); }); }
 #cursor { top: 0; left: 0; border-radius: 50%; pointer-events: none; z-index: 1000; } #cursor>div { border-radius: 50%; width: 1.25rem; height: 1.25rem; background: black; transition: transform 0.5s ease, opacity 0.35s ease; } #cursor.hide { background: red; }
 <div id="cursor" data-cursor> <div></div> </div> <button data-hide-cursor type="submit" class="submit-mail"> Submit </button>

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