IDs in an HTML document need to be unique. You are generating an HTML document with duplicate IDs - for example, every row has a button with
id="pending"
. When you ask the document for the element with the ID "pending", it will only return a single element. In this case, it returns the first one it finds, but there is no guarantee that it will always pick a specific one.
You need to change your code to use a unique ID for each element. Alternatively, find a different way to identify the elements you want to work with. For example, using
Event Delegation[
^] :
<td><label name="pending">Pending</label></td>
<td><button name="accept">Accept </button></td>
<td> <button name="reject">Reject</button></td>
document.getElementById("YourTableId").addEventListener("click", function(e) {
let target = e.target;
if (target.tagName !== "BUTTON") { target = target.closest("button"); }
if (!target) { return; }
let statusText, statusColor;
if (target.name === "accept") {
statusText = "Accepted";
statusColor = "green";
} else if (target.name === "reject") {
statusText = "Rejected";
statusColor = "red";
} else {
console.warn("Unknown button:", target);
return;
}
const pending = target.closest("tr").querySelector("label[name='pending']");
pending.innerHTML = statusText;
pending.style.backgroundColor = statusColor;
});