Issue
I want to add an event listener to icon img which first one to delete and second for edit. How can I select img from template string in this code?
function renderStudentList() {
tableBody.innerHTML = "";
studentList.map((student) => {
const studentRow = `
<tr>
<td>${student.id}</td>
<td>${student.name}</td>
<td>${student.surname}</td>
<td>${student.birthday}</td>
<td>${student.age}</td>
<td>${student.gender === "M" ? "Male" : "Female"}</td>
<td>
<img src="./icons/delete.svg" alt="delete">
<img src="./icons/edit.svg" alt="edit">
</td>
</tr>
`;
tableBody.insertAdjacentHTML("beforeend", studentRow);
})
}
Solution
You can set up the click handlers while generating the template. This way you don't have to query them afterwards. Like so:
function deleteClickHandler() {}
function editClickHandler() {}
function renderStudentList() {
tableBody.innerHTML = "";
studentList.map((student) => {
const studentRow = `
<tr>
<td>${student.id}</td>
<td>${student.name}</td>
<td>${student.surname}</td>
<td>${student.birthday}</td>
<td>${student.age}</td>
<td>${student.gender === "M" ? "Male" : "Female"}</td>
<td>
<img src="./icons/delete.svg" alt="delete" onclick="deleteClickHandler()" />
<img src="./icons/edit.svg" alt="edit" onclick="editClickHandler()" />
</td>
</tr>
`;
tableBody.insertAdjacentHTML("beforeend", studentRow);
});
}
Answered By - yousoumar
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.