skip to Main Content

Hello everyone in the group,

I wrote a JavaScript snippet to retrieve the elements that I click on. However, when I declare the variable using "var," it only shows the last clicked element as the result. But when I use "let" for declaration, it gives me the desired outcome (retrieving the correct element that I click on).

Below is the image when I declare using "var":enter image description here
And here is the image when I use "let":enter image description here

I hope someone can help me clarify why, when declaring with "var," it only prints the last element. Thank you, everyone, for your assistance.

I want to display the element that I click on.

3

Answers


  1. Click on h2 elements to get clicked elements

    click on any elements to get element printed on console.

    let elems = document.querySelectorAll("h2");
    
      //Make DOM node array iterable
      for (let elem of elems) {
          //event listener handler function
          elem.addEventListener("click", clickHandler);
      }
    
      function clickHandler(event) {
          console.log(event.target);
      }
    <!DOCTYPE html>
    <html lang="en">
    
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>
    <style>
      h2 {cursor : pointer;}
    </style>
    <body>
        <h2>ONE</h2>
        <h2>TWO</h2>
        <h2>THREE</h2>
        <h2>FOUR</h2>
        <h2>FIVE</h2>
    </body>
    
    </html>
    Login or Signup to reply.
  2. What’s the actual problem in this case? Since you’re saying:

    But when I use "let" for declaration, it gives me the desired outcome

    You’ve solved your own problem. Or is let something you don’t want to use? In that case please explain why. Otherwise, just use let.

    Maybe it’s also a good idea to look at this post which explains the differences between var and let.

    Login or Signup to reply.
  3. There is significant difference between the usage of var and let keywords in javascript.

    • Variables declare by let will only be available inside the block of the
      function or method in which it is being declared. which is known as
      blocked-scope.
    • When you define a variable with let javascript’s Hoisting will not be
      allowed.
    • Variables declared on var will be available even outside of the method or
      function that they are created on. Which is known as global-scope
      javascript.
    • When you define a variable with var javascript will allow hoisting onto
      it

    In your case, if you are using let and it solves the problem then most probably it can be a scope-related issue.

    If you want to read more about Hoisting please follow this link
    here.

    If you want to learn more about scopes follow the link here.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search