0

Would someone please explain why this isn't working?

HTML

<p>
    <button class="selectable">Button</button>
</p>

Javascript

var selectable = document.getElementsByClassName('selectable');

selectable.onclick = function() {
    alert("Success");
}

https://jsfiddle.net/qpmsw5yg/

Thanks,

Justin

Justin Breen
  • 126
  • 3
  • 11

2 Answers2

3

selectable is a HTMLCollection not an Element. So you should listen to selectable[0].

Updated JSFiddle : https://jsfiddle.net/NeekGerd/qpmsw5yg/1/

Yoann
  • 3,020
  • 1
  • 24
  • 34
  • 1
    This answer worked, thank you. Would also be helpful to know how to apply to all which the answer below showed using a loop. Thanks to everyone! – Justin Breen Dec 09 '15 at 02:56
2

Because document.getElementsByClassName returns a collection. If you want to set a handler on a node, you have to specify an individual node.

function onSelectableClick() {
    alert('Success');
}

var selectables = document.getElementsByClassName('selectable');
for (var i = 0; i < selectables.length; i++) {
    selectables[i].onclick = onSelectableClick;
}
Mike Cluck
  • 31,869
  • 13
  • 80
  • 91