gabor aron
gabor aron

Reputation: 410

How to get id from a button if I know the name - javascript

I have some buttons, with same name anOldFile and I want to get theirs id, or innerHTML if I clicked. I think this is a good start, but I don't know how to continue, if this is good:

    document.getElementsByName('anOldFile').addEventListener('click', changeOffCanvasContent(this));

    function changeOffCanvasContent(e) {
         //???
    }

Upvotes: 0

Views: 75

Answers (2)

Bartosz Gawron
Bartosz Gawron

Reputation: 187

you have several problems there. Fist of all getElementsByName returns array of node elements, so you have to addEventListener to each one of them. Secondly you are registering eventListener function incorrectly. You should not call a handler function in addEventListener, but just pass a handler name. Thridly in the function definition you can get hold of element by referencing target element as follows:

Whole code snippet that does the job should look as follows:

var elements = document.getElementsByName('anOldFile');

function changeOffCanvasContent(e) { console.log(e.target.innerHTML); console.log(e.target.id); }

for(var i = 0; i< elements.length-1; i++){ elements[i].addEventListener('click', changeOffCanvasContent); }

Upvotes: 1

Satpal
Satpal

Reputation: 133403

As getElementsByName() returns a nodelist, you need to iterate and bind event handler to each element and just pass the function reference.

document.getElementsByName('anOldFile').forEach(function (elem) {
    elem.addEventListener('click', changeOffCanvasContent);
});

It will set the context of this to element which invoked the event

function changeOffCanvasContent(e) {
    console.log(this.id);
    console.log(e.target.id);
}

Upvotes: 2

Related Questions