const Form = document.querySelector(".tracker-form"),
Name = document.querySelector(".tracker-name"),
Date = document.querySelector(".tracker-date"),
Amount = document.querySelector(".tracker-amount"),
Table = document.querySelector(".tracker-table"),
tableRow = document.createElement("tr");
function deleteRow(event) {
const button = event.target;
const row = button.parentNode;
tableRow.removeChild(row);
}
function addExpense() {
Form.addEventListener("submit", event => {
const tableName = document.createElement("td");
const tableDate = document.createElement("td");
const tableAmount = document.createElement("td");
const delButton = document.createElement("button");
delButton.innerHTML = "X";
delButton.addEventListener("click", deleteRow);
Table.appendChild(tableRow);
tableRow.appendChild(tableName);
tableRow.appendChild(tableDate);
tableRow.appendChild(tableAmount);
tableRow.appendChild(delButton);
tableName.innerHTML = Name.value;
tableDate.innerHTML = Date.value;
tableAmount.innerHTML = Amount.value;
Name.value = "";
Date.value = "";
Amount.value = "";
event.preventDefault();
})
}
function init() {
addExpense();
}
init();
I'm making an expense tracker. When I enter a value in name, date, amount, values, and 'x' button display on each table. And I want to make a row removed when I click 'x' button. But it doesn't work. Can anyone tell me why?
You can simply remove the closest tr element:
function deleteRow(event) {
event.target.closest('tr').remove();
}
You need to distinguish between parentNode
.
parentNode: The parentNode property returns the parent node of the specified node, as a Node object.
and closest
The closest() method searches up the DOM tree for the closest element which matches a specified CSS selector
$(".deleteRowButton").on("click", function(event){ var $closest = event.target.closest('tr'); var $parentNode = event.target.parentNode; // It just return `td` instead. console.log({closest: $closest, parentNode: $parentNode}); $closest.remove(); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table> <tr><td>foo</td> <td><a class="deleteRowButton">delete_row</a></td></tr> <tr><td>bar bar</td> <td><a class="deleteRowButton">delete_row</a></td></tr> <tr><td>bazmati</td> <td><a class="deleteRowButton">delete_row</a></td></tr> </table>
Visualize output like below:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.