1

i have button with class but doesn't have Id, this is Button Tag ,i want to any sound when i click that button so i called it by getElementsByClassName and added this function

var stopMusicExt = document.getElementsByClassName("slide-control-button-next slide-lockable")[0];
stopMusicExt.onclick = function() {
this.pause();
this.currentTime = 0;
}

but every time browser show this error


Uncaught TypeError: Cannot set property 'onclick' of undefined


what can i do to solve this problem.please?

beko
  • 11
  • 3
  • Where in the page is the script located? Is it directly on the window or is it in an onload function? – Will P. Oct 19 '17 at 21:43

2 Answers2

2

Also, don't use event properties! Use addEventListener (MDN) as a modern standard instead:

var stopMusicExt = document.getElementsByClassName("btn cs-button inflexible slide-control-button-next slide-lockable")[0];

stopMusicExt.addEventListener('click', function() {
  this.pause();
  this.currentTime = 0;
});

To be explicit, you may add an id attribute to your button element:

<button id="myButton" class="dtn cs-button inflexible etc">

and use getElementById() method to access it

var stopMusicExt = document.getElementById("myButton");
dhilt
  • 13,532
  • 6
  • 48
  • 67
  • i tried this `var stopMusicExt = document.getElementsByClassName(".button.btn.cs-button.inflexible.slide-control-button-next.slide-lockable")[0]; console.log(stopMusicExt);` but it show to me that the classname is undefined – beko Oct 20 '17 at 13:50
  • @beko Due to [specification](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName) "class names are separated by whitespace", no dots are needed, sorry for confusing! I also updated the answer and added `id`-based variant. – dhilt Oct 20 '17 at 14:22
0

Your selector seems to not have found the class names you were looking for, hence why the onclick handler wasn't bound to the element you wanted. Take a look at the example below:

var stopMusicExt = document.getElementsByClassName("slide-control-button-next slide-lockable")[0];
stopMusicExt.onclick = function() {
  alert('clicked');
}
.slide-control-button-next {
  background: red;
  height: 100px;
  width: 100px;
}
<div class="slide-control-button-next slide-lockable">

</div>
jonhurlock
  • 1,478
  • 1
  • 15
  • 28
Xenyal
  • 1
  • 3
  • yes you are right, the problem in my code is that the classname is undefined, but how it isn't undefined and i use it without any change in class name ? – beko Oct 20 '17 at 13:47