0

I'm new to java script and have a long way to go off learning, and attempted to make something but it doesn't not work.

Here's the code:

var LIS = document.getElementsByClassName("Links")[0].querySelector("ul").querySelector("li").querySelector("a");

for (let Index in LIS){
  LIS[Index].mouseenter = function(){
    console.log("Test");
  };
};

Here's the error I get Img

function main(){
    document.getElementsByClassName("Links")[0].querySelector("ul").querySelector("li").querySelector("a").onmouseenter = function(){
        console.log("Test")
    }
}

This one didn't log anything in the console.

0stone0
  • 34,288
  • 4
  • 39
  • 64
jd8
  • 1
  • Share your html – 0stone0 Mar 12 '23 at 17:46
  • 3
    [Please do not upload images of code/data/errors.](//meta.stackoverflow.com/q/285551) – Michael M. Mar 12 '23 at 17:46
  • 1
    Seems like `document.getElementsByClassName("Links")` does not find anything. Either that's not the correct class name, or you're trying to look up the documents before they exist in the document. – VLAZ Mar 12 '23 at 17:47
  • 1
    Unrelated to the current error but `for (let Index in LIS)` is also wrong: since you use `.querySelector()` that means `LIS` will be a single DOM element and you'd be iterating over that element's attributes, rather through each item in a collection. – VLAZ Mar 12 '23 at 17:50
  • 1
    What is unclear about an error message such as _“Cannot read property `querySelector` of `undefined`”_? You can’t read properties of `undefined`, but that’s what happens at `document.getElementsByClassName("Links")[0].querySelector` because `document.getElementsByClassName("Links")[0]` is `undefined`; it’s trying to get `querySelector` off of `undefined` — not possible. If you don’t know why `document.getElementsByClassName("Links")[0]` is `undefined`, use the debugger or look at intermediate values: `console.log(document.getElementsByClassName("Links"));`. – Sebastian Simon Mar 12 '23 at 18:32
  • 1
    Is your `` which solves this problem and many more. – Sebastian Simon Mar 12 '23 at 18:33

0 Answers0