i've started learning dom recently. I'm planning on making a website which has a few buttons upon click those buttons, the website makes a drum sound(different drum sound for different button).
So, i wanted to experiment with this
keyword in js. As far as my knowledge this
should return the name of the object.
So, i expect this code to return me button
object but instead it returns Window {parent: Window, opener: null, top: Window, length: 0, frames: Window, …}
here is my js file -
var buttons = document.querySelectorAll('.drum')
console.log(buttons)
buttons.forEach(button => button.addEventListener('click', () =>{
console.log(this)
}
))
But strangely enough the following code gives me the desired object, i.e gives button
object like so -
<button class = "a drum">w</button>
here is the code associated with this result -
var num = document.querySelectorAll('.drum').length
for (var i = 0; i < num ; i++){
document.querySelectorAll('.drum')[i].addEventListener('click', function(){
console.log(this);
})
}
As far as i can see, they both are the same code, just different the way the were written. So, please explain why im getting that behaviour.
if anyone is interested, here is the html file -
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Drum Kit</title>
<link rel="stylesheet" href="styles.css">
<link href="https://fonts.googleapis.com/css?family=Arvo" rel="stylesheet">
</head>
<body>
<h1 id="title">Drum Kit</h1>
<div class="set">
<button class="w drum">w</button>
<button class="a drum">a</button>
<button class="s drum">s</button>
<button class="d drum">d</button>
<button class="j drum">j</button>
<button class="k drum">k</button>
<button class="l drum">l</button>
</div>
<script src="./index.js"></script>
</body>
</html>
Any help is appreciated.Thanks.