I want to create a remove button in each row of a table, so I created a removeButton
element in JavaScript and appended it to each row. However, it moves to the last row whenever I create new rows.
Here is my table when i create a new row
Code:
I created a removeButton
element:
const removeButton = document.createElement("button");
removeButton.innerText = "Remove book";
removeButton.className = "table__remove-btn";
And append it to each row when update the table:
function updateTable() {
table.innerHTML =
"<tr><th>Title</th><th>Author</th><th>Pages</th><th>Is read?</th></tr>";
if (myLibrary.length != 0) {
const tableContent = document.createDocumentFragment();
myLibrary.forEach((value) => {
const tableRow = document.createElement("tr");
const titleCell = document.createElement("td");
const title = document.createElement("p");
const author = document.createElement("td");
const pages = document.createElement("td");
const isRead = document.createElement("td");
title.innerText = value.title;
titleCell.appendChild(title);
titleCell.appendChild(removeButton); // <------------------- Here!
titleCell.className = "table__title-cell";
tableRow.appendChild(titleCell);
author.innerText = value.author;
tableRow.appendChild(author);
pages.innerText = value.pages;
tableRow.appendChild(pages);
isRead.innerText = value.isRead ? "Yes" : "No";
tableRow.appendChild(isRead);
tableContent.appendChild(tableRow);
});
table.appendChild(tableContent);
}
}
How i can solve it? I want to have the removeButton
on each row
2
Answers
What happens is that you create only one element using document.createElement(). When the browser reads this code, it only allocates one element in the memory, and it is rereferenced each time you run titleCell.appendChild(element), resulting in only the last row keeping this button. For this code to work the way you’d like, you have to create a new button element on each iteration of the forEach loop. I have submitted two variations below. One using a predefined function to create the buttons, and one with the code inline with updateTable().
Predefined function
and then you use this function inside the updateTable() function
Or, you can place all of the code inline with updateTable(), like this:
<thead>
and<tbody>
if (myLibrary.length != 0) {
when using forEach. It will either loop or notel
(to target elements) andelNew()
to create new onescreateRow
function that creates a row, that way you can append a single book whenever it’s needed