So I have this expense tracker website, it's just a beginner JavaScript project. I have an issue with deleting rows. If I click on the delete button it always deletes the first row below the heading, rather than deleting the row which I want to delete.
HTML Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="styles.css" />
<script
src="https://kit.fontawesome.com/60cb322ae0.js"
crossorigin="anonymous"
></script>
<title>Expense Tracker</title>
</head>
<body>
<div class="wrapper">
<h1>Expense Tracker</h1>
<form action="">
<label for="">Name</label>
<input
class="name"
type="text"
placeholder="Where was the expense made"
/><br />
<label for="">Date</label>
<input class="date" type="date" />
<label for="">Amount</label>
<input class="amount" type="number" /><br />
<button class="btn" type="submit">Add Expense</button>
</form>
</div>
<table>
<tr>
<th>Name</th>
<th>Date</th>
<th>Amount</th>
<th></th>
</tr>
</table>
<script src="index.js"></script>
</body>
</html>
JavaScript Code
const name = document.querySelector(".name");
const date = document.querySelector(".date");
const amount = document.querySelector(".amount");
const btton = document.querySelector(".btn");
const table = document.querySelector("table");
//Event
btton.addEventListener("click", toTable);
table.addEventListener("click", toDelete);
//fucntion
function toTable(event) {
event.preventDefault();
//creating table row
const tableRow = table.insertRow();
//creating table definitions
const tableName = tableRow.insertCell();
const tableDate = tableRow.insertCell();
const tableAmount = tableRow.insertCell();
const tableDelete = tableRow.insertCell();
tableDelete.classList.add("trash");
//assigning values
tableName.innerHTML = name.value;
tableDate.innerHTML = date.value;
tableAmount.innerHTML = amount.value;
tableDelete.innerHTML = "<i class='far fa-trash-alt'></i>";
//making the input fields clear
name.value = "";
date.value = "";
amount.value = "";
}
function toDelete(event) {
var item = document.querySelector(".trash");
item = item.parentElement;
item.remove();
}
Sorry for this mess of a code, I just started coding.
document.querySelector(".trash")selects the first element with that class in the document. You need to select the parent of the element that the event actually happened upon.