AshBringer
AshBringer

Reputation: 2673

How to add listener in td element?

Why is the listener works only on one td ?

Here is the fiddle.

document.getElementById(x).addEventListener("click",showStatusDialog);

this line works only on one item while the alert in comment works well for all td items.

Upvotes: 0

Views: 1216

Answers (2)

epascarello
epascarello

Reputation: 207527

Because when you add the rows with innerHTML you destroy all of the events that are attached to its siblings. So each row you add, you destroy the previous events added. That is why only the last element has the click event.

You should either use event delegation or build the row with document.createElement() and appendChild()

//outside the loop
var tbody = document.querySelector("#tfhover tbody");


var tr = document.createElement("tr");
var td1 = document.createElement("td");
td1.innerHTML = json2[i].rank;
var td2 = document.createElement("td");
td2.innerHTML = json2[i].content;
var td3 = document.createElement("td");
td3.innerHTML = json2[i].UID;
td3.id = "uid"+i;
td3.addEventListener("click",showStatusDialog);
tr.appendChild(td1);
tr.appendChild(td2);
tr.appendChild(td3);
tbody.appendChild(tr);

Upvotes: 1

Edwin Reynoso
Edwin Reynoso

Reputation: 1541

I understand you're code even though it's a bit messy, yet I'm not sure if I should give you an answer because I'll be teaching you bad practices by the way your code is. But what you will want to learn is about Event Delegation here are some really good sources:

Source 1

First link is by codepen and it says I needed some code so I'm pretending this is code.

Source 2

Source 3

Source 4

Attention:

Please do not vote down. I didn't want to comment this because it would not look good to read. So if someone is going to provide a answer to the direct question please feel free. I just believe @BipBip would like to learn about event Delegation.

Thank You.

Upvotes: 1

Related Questions