Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

const a = document.querySelector("#stages a");

console.log(a);

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading