celli celli - 6 months ago 19
jQuery Question

Javascript Classname Click without jQuery

I am trying to convert this code below to vanilla javascript because we cannot use jQuery

if (isSafari) {
$('.buttonClassName').click(function() {
// do something
});
}


I was trying something like this, but it doesn't work:

if (isSafari) {
document.getElementByClassName("buttonClassName").onclick = function () {
// do something
};
}


What javascript can I use without jQuery

Answer
var elements = document.getElementsByClassName('buttonClassName');
for(var i = 0; i < elements.length; i++) {
    var element = elements[i];
    element.onclick = function() {}
}