Joel G Mathew
Joel G Mathew

Reputation: 8061

Get the id of a link when clicked using Javascript

I'm new to Javascript, and trying to design a form with elements that are created and deleted by clicks on links without submitting a form.

The script depends on getting the unique id of a clicked button (css and <a> link), and calculating the id of the row containing the link, and then deleting the entire <tr> element.

For this, I'm trying to get the id of a clicked link. The link and the elements it is embedded in, is itself generated by javascript on clicking another button.

I tried the following:

var btnDel=document.createElement("a");
btnDel.id="NS_D"+count;
btnDel.className="btn btn-danger";
btnDel.addEventListener('click', function() 
{            
    alert(e.id);
}, false);
var btnText=document.createElement("span");
btnText.className="btn-label";
btnText.innerHTML="Delete";
btnDel.appendChild(btnText);            
td.appendChild(btnDel);     

Though the button is generated, I'm not getting an alert as expected. Where can I have gone wrong?

Upvotes: 1

Views: 1482

Answers (2)

RichieHindle
RichieHindle

Reputation: 281405

You need use this rather than e:

alert(this.id);

in your event handler.

Demo here.

(You also need to get used to running your code with the Console visible - that would have told you that the reason you weren't seeing your alert is that e doesn't exist.)

Upvotes: 2

MrCode
MrCode

Reputation: 64526

In the event handler, this refers to the element, so you can do:

alert(this.id);

To get to the <tr> you can go up the tree using parentNode:

console.log(this.parentNode.parentNode);

MDN docs

Upvotes: 2

Related Questions