Lolo Lolo - 1 month ago 6
Javascript Question

Javascript : Function only works with getElementById

I have a function to attach a event.

function addEvent(object, type, callback) {
if (object == null || typeof(object) == 'undefined') return;
if (object.addEventListener) {
object.addEventListener(type, callback, false);
} else if (object.attachEvent) {
object.attachEvent("on" + type, callback);
} else {
object["on"+type] = callback;
}
};


And a tiny button to test

<a href="#" class="btn btn-primary btn-toggle" id="btn-toggle-action">Toggle</a>


I try to call it but I've seen

addEvent(document.getElementById('btn-toggle-action'), 'click', function(e) {});
WORK

addEvent(document.getElementByClassName('btn-toggle'), 'click', function(e) {});
DON'T WORK

addEvent($('.btn-toggle'), 'click', function(e) {}):
DON'T WORK

addEvent($('#btn-toggle-action'), 'click', function(e) {});
DON'T WORK

I'd like to understand why it can't works with allmethods

Answer

Firstly, write error: document.getElementByClassName should be document.getElementsByClassName, because it select mutiple elements.

jquery selector is diffrent from native selector, see document-getelementbyid-vs-jquery

You can use more powerful native selector like:

document.querySelector('#btn-toggle-action')

document.querySelectorAll('.btn-toggle')

Comments