Chris Abrams
Chris Abrams

Reputation: 42390

Javascript get element that was clicked based on ClassName

First, I would have created this example in JSFiddle but they are in read-only mode.

I would like to get the specific element that was clicked based on a class.

var button = document.getElementsByClassName("mybutton");
button.onclick = function() {
    //how do I reference the specific button that was clicked?
};

 

<button class="myclass">Button 1</button>
<button class="myclass">Button 2</button>

No jQuery answers please; that is not an option here.

Upvotes: 0

Views: 371

Answers (2)

zzzzBov
zzzzBov

Reputation: 179046

it's not document.getElementByClassName, it's document.getElementsByClassName.

See the difference yet?

It's easy to overlook:

document.getElementByClassName
document.getElementsByClassName
                   ^

The former doesn't exist unless you define it, the latter only works in modern browsers. getElementsByClassName will return a node list, which you need to iterate over to attach event listeners to each node.

var i,
    l,
    buttons,
    button;

function clickHandler(e) {
    console.log(this);//the button that was clicked on
}
buttons = document.getElementsByClassName('mybutton');
for (i = 0, l = buttons.length; i < l; i++) {
    button = buttons[i];
    button.onclick = clickHandler;
}

Upvotes: 1

sazh
sazh

Reputation: 1832

The first argument in your event handler will be a reference to the event

var button = document.getElementByClassName("mybutton");
button.onclick = function(e) {
    //e.Target is a reference to your button
};

Upvotes: 0

Related Questions