Reputation: 85
I am trying to get the id of a button (link) that I created in javascript within the onclick method.
I tried this code, but it always displays the id of the last element in the unordered list in the alert, instead of the item that I click.
while (index != -1) {
var select = document.getElementById("recipes");
var opt = document.createElement("li");
opt.className = "list-group-item";
var link = document.createElement("a");
link.id = response.substring(0, index);
link.onclick = function () {
alert(link.id);
};
link.textContent = response.substring(0, index);
select.appendChild(opt);
opt.appendChild(link);
response = response.substring(index + 4);
index = response.indexOf("~,;~");
}
Upvotes: 2
Views: 91
Reputation: 93213
All event-listeners in javascript give the opportunity to access to target element using this
.
Thus :
link.onclick = function () {
alert(this.id);
};
And Not :
link.onclick = function () {
alert(link.id);
};
Upvotes: 2
Reputation: 467
You can simply use alert(this.id);
instead.
this
always points to the element that called the function, in this case the specific instance of link
you click on.
Upvotes: 0
Reputation: 2288
Your problem is scope. In a situation like this you have to close the values around the event handler so that they are not changed by the loop. Here is an example:
while (index != -1) {
var select = document.getElementById("recipes");
var opt = document.createElement("li");
opt.className = "list-group-item";
var link = document.createElement("a");
link.id = response.substring(0, index);
(function (_link) {
_link.onclick = function () {
alert(_link.id);
};
})(link);
link.textContent = response.substring(0, index);
select.appendChild(opt);
opt.appendChild(link);
response = response.substring(index + 4);
index = response.indexOf("~,;~");
}
Using this
will also work as others have noted. However, it is important to know why using link.id
does not work here which is a result of scope.
Upvotes: 0