How to find index of an Object inside of querySelectorAll?
I need index of element inside of NodeList...
Something like this, but it does not work.
25 Replies
what are you trying to do?
Get index of that element in array, or nodeList in this case.
If I have 5 elements vertically stacked, I need index of that one that I clicked.
Got it!
I was testing too, and just noticed indexOf doesn't exist on NodeList
good catch!
Yeah! xD Was really confusing me...
Unknown User•2y ago
Message Not Public
Sign In & Join Server To View
You're passing in an
HTMLClickEvent
, naming it image
, and then searching through an array of HTMLElement
s from the querySelector
. That's never going to find the image, and indexOf
returns -1
if it can't find anythingUnknown User•2y ago
Message Not Public
Sign In & Join Server To View
I don't think it'll work like that either, you're comparing an
HTMLEventTarget
with HTMLElement
, they're not quite the same, and object comparisons in Javascript don't compare the values of the objects anyway, they only return if the reference is the sameUnknown User•2y ago
Message Not Public
Sign In & Join Server To View
what do you need the index for?
Unknown User•2y ago
Message Not Public
Sign In & Join Server To View
do the images have ID's?
Unknown User•2y ago
Message Not Public
Sign In & Join Server To View
I'd probably either stick an ID on there, or maybe even better in this case, a
data-
attribute with the order. Then you have something very simple to compare, and there's no need to loop over the entire image array
alternatively, if the img tags are all that exists in the parent element, each one will have a previousElementSibling
and nextElementSibling
, but I doubt they're not wrapped in something, and chaining those with parentNode
gets super unreadable and janky very quicklyUnknown User•2y ago
Message Not Public
Sign In & Join Server To View
like this?
or like this?
Unknown User•2y ago
Message Not Public
Sign In & Join Server To View
Hm, so then every time you get an element, whether it's from a click event or a querySelector, it'll have the properties
nextElementSibling
and previousElementSibling
, which if you clicked the one with alt="2"
would contain the ones with 1 and 3 respectively
if you store that element reference as currentImage
or something, you can keep accessing either next or previous sibling and overwriting the currentImage when you push the arrow keys, or just overwriting it wholesale whenever you click another image in the listUnknown User•2y ago
Message Not Public
Sign In & Join Server To View
no worries, glad to help!
Unknown User•2y ago
Message Not Public
Sign In & Join Server To View
pretty sure it's supposed to return
null
if there is none
haha, nice, thanks 😄Unknown User•2y ago
Message Not Public
Sign In & Join Server To View
np 🙂