Hey everyone, I've been experimenting with different solutions for a few hours now but I'm still stuck on this problem. I have a function that takes JSON as input -
I can create an 'a'
element: CHECK
I can set all the element properties like 'href'
: CHECK
I can append 'a'
with required element tags: CHECK
But I am unable to set the
a.addEventListener("click", function () { alert("clicked - " + a.id) }, false);
Every time I click on any href, it displays the last value
function setTags(tagsJson) {
var obj = JSON.parse(tagsJson);
var a = null;
var linkText = null;
for (var i = 0; i < obj.length; i++) {
if (typeof (obj[i].Tag_name) === 'undefined' || obj[i].Tag_name === null) {
// DO NOTHING
}
else
{ a = document.createElement('a');
linkText = document.createTextNode(obj[i].Tag_name);
a.appendChild(linkText);
a.href = "#";
a.textContent = obj[i].Tag_name;
a.className = "badge badge-success";
document.getElementById("tags").appendChild(a);
// THE ISSUE LIES HERE
a.addEventListener("click", function () { alert("clicked - " + a.textContent) }, false);
}
}
}
For example, if the JSON contains the following values
{\"Tag_id\":12,\"Tag_name\":\"Aston Martin\"},{\"Tag_id\":13,\"Tag_name\":\"Cars\"}]"}
It should display unique text in 'textContent'
such as 'Aston Martin', 'Aston' and 'Cars' but when clicking on any item, the alert only shows Cars
even though the link's text displays the correct values.
https://i.sstatic.net/OiwO2.png
Based on the screenshot above, the text values seem fine, but the addEventListener only displays the last value on CLICK
I believe there is something I am not grasping about addEventListener
?
How can I resolve this issue?
Cheers