Keavon
Keavon

Reputation: 7493

JS call code block upon clicking one of many items with specific class

I have a page with a bunch of buttons that all have a class (actually two classes, each separated by a space; I can use either or both). I need to call a function or a block of code (let's say an alert for this example) when the user clicks one of these buttons with this class. I do not have access to the HTML so the link itself can't call the function. I don't need to know which button. How do I do this with pure JavaScript (no jQuery)?

Upvotes: 0

Views: 124

Answers (2)

nzn
nzn

Reputation: 838

you can do something like this:

var btns = document.getElementsByClassName('test');
for (var i = 0; i < btns.length; i++){
    btns[i].onclick = function(){
        alert(this.innerHTML)
    }
}

demo

Upvotes: 2

jrpotter
jrpotter

Reputation: 161

Just loop through each one by class and bind the event handler.

var elems = document.getElementsByClassName('cls');
for(var i = 0; i < elems.length; i++) {
    elems[i].onclick = function() {
        alert('Clicked');
    };
}

Upvotes: 1

Related Questions