Home > Enterprise >  JavaScript: OnClick with multiple elements return "windows" under this keyword
JavaScript: OnClick with multiple elements return "windows" under this keyword

Time:05-09

I am trying to bind all <a> elements to have onclick function. And while variable a is a, when I try to use keyword this inside of onclick it returns me Window object. Code:

<!DOCTYPE html>
<html lang="pl">
<head>
    <meta charset='utf-8'>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta http-equiv='X-UA-Compatible' content='IE=edge'>
</head>
<body>
<div id="stages">
    <div><p>Część I</p></div>
    <div><a data="audio/01-1-1.mp3">Rozdział  1</a><div></div><p>44:10</p></div>
    <div><a data="audio/02-1-2.mp3">Rozdział  2</a><div></div><p>20:06</p></div>
    <div><a data="audio/03-1-3.mp3">Rozdział  3</a><div></div><p>19:16</p></div>
    <div><a data="audio/04-1-4.mp3">Rozdział  4</a><div></div><p>25:29</p></div>
    <div><a data="audio/05-1-5.mp3">Rozdział  5</a><div></div><p>32:16</p></div>
    <div><a data="audio/06-1-6.mp3">Rozdział  6</a><div></div><p>13:06</p></div>
    <div><a data="audio/07-1-7.mp3">Rozdział  7</a><div></div><p>28:38</p></div>
    <div><a data="audio/08-1-8.mp3">Rozdział  8</a><div></div><p>51:59</p></div>
</div>

<script>
const a = document.querySelector('#stages a')
console.log(a)
a.onclick = () => {
    console.log(this);
}
</script>
</body>
</html>

CodePudding user response:

In order to use this, you need to create a regular anonymous function rather than an arrow function.

const anchors = [...document.querySelectorAll("#stages a")];

anchors.forEach(a => {
   console.log(a);

   a.onclick = function () {
      console.log(this);
   };
});

CodePudding user response:

You can use event delegation to get the desired result. It'll even provide you with more flexibility, like events for dynamic elements:

document.addEventListener('click',function(e){
  if(e.target && e.target.nodeName == 'A'){
    console.log(e.target.getAttribute("data-yourDataValue"));
    return false;
  }
});

The highest scoring answer here: What properties can I use with event.target? will tell you which properties you can access through event.target, which I can imagine will be very helpful to you as well when using this.

Edit: Added example on how to get data attribute values as requested.

CodePudding user response:

It's normal, as you're in window closure and you use an arrow function, if you need to have access to your element, you can add a prop to your arrow function like this

<script>
      const a = document.querySelector("#stages a");
      console.log(a);
      a.onclick = (e) => {
        console.log(e.target);
      };
</script>
  • Related