querySelectorAll not working
Hi everyone
I realise this :
https://codepen.io/alpha_66/pen/MWxoLZJ
the problem appear when I use querySelectorAll to select all li tag I get this message
if I just use querySelector('li'); is working but only for one element
can I some idea about how to fix this problem ?
thanks
16 Replies
That one returns an array, you have to loop over the array and add listeners to each record yourself.
MDN Web Docs
Document: querySelectorAll() method - Web APIs | MDN
The Document method querySelectorAll()
returns a static (not live) NodeList representing a list of the
document's elements that match the specified group of selectors.
you forgot
; i++
in the for loop descriptorthanks
I try like this :
I have this message :
couleur[i].classList.add
might workthe new one:
now I have :Uncaught TypeError: couleur.addEventListener is not a function
you didn't add [i] to the first addEventListener
OK I had it
I'd recommend reading up on how for loops and scope work. You're looping over couleur, one by one, but that doesn't change the value of couleur. Inside the for loop, you can access the children of couleur by adding
[i]
. You're indexing into the array of couleur, going to index i
, and access that particular child
when you read those errors, they say exactly what's wrong. You're trying to access the property add
or remove
on the classList
property of the array couleur
, which doesn't have a classList
property, so it's producing an error
it says "cannot read properties of undefined (reading 'add')" because couleur.classList
is undefined on an array. In this particular array, it is accessible on its children though
I'd recommend trying to figure this one out on your own, based on ^ that, but if you want to have the solution You just need to add [i] to the couleur in the two event listenersbtw, different from the question how to do the loops.
you are adding/removing the same class on mouse over and mouse out. you do know you can use css hover?
thanks for your message but the exercise need JS