Preferably, you should use document.createElement()
to create new elements, and either ParentNode.append()
or Node.appendChild()
for adding that element to the DOM.
The advantages of using them are:
- No (better: less) risk of invalidating your HTML
- No chance of accidentally removing listener of existing elements
- Easier configuration of the newly created element(-s) (like adding listener)
One downside of using them is, that it makes your JavaScript quite a bit more lengthy.
However, using said method of adding the new <tr>
allowed me to easily reference it for removal upon pressing the cancel-button.
That means, with easy referencing, it is easy to dynamically add rows with the behavior you wanted.
Sidenote
I have replaced <td><strong></strong></td>
with <th></th>
since the apparent purpose of the nested elements were exactly what <th>
is semantically about.
I have also added the click-listener to a button, which contains the cancel-icon, since adding a click-listener to something different than <a>
, <button>
or <input>
(meaning: any element which is not inherently clickable) is more difficult to set up to be accessible. You can still stylize the button to be without border and background, so that only the image is visible as you wanted.
const itemTable = document.querySelector("#item-table");
const typeField = document.querySelector("#type-field");
document.querySelector("#add-item-btn").addEventListener("click", () => {
let tr = document.createElement("tr");
tr.classList.add("hole-element");
let th = document.createElement("th");
th.innerHTML = typeField.value + ":";
th.setAttribute("style", "text-align: left");
tr.append(th);
let td = document.createElement("td");
tr.append(td);
let input = document.createElement("input");
input.setAttribute("type", "text");
td.append(input);
td = document.createElement("td");
tr.append(td);
let button = document.createElement("button");
button.classList.add("cancel-icon");
button.addEventListener("click", () => {
tr.remove();
});
td.append(button);
let img = document.createElement("img");
img.setAttribute("src", "icon/cancel.png");
img.setAttribute("height", "25px");
button.append(img);
itemTable.append(tr);
typeField.value = "";
});
th {text-align: left}
.cancel-icon{
transition: 0.3s;
margin-left: 15px;
}
.cancel-icon:active{transform: scale(0.9)}
<table id="item-table">
<tr>
<th>Name: </th>
<td><input type="text"></td>
</tr>
<tr>
<th>Unit: </th>
<td><input type="text"></td>
</tr>
<tr>
<th>Price: </th>
<td><input type="text"></td>
</tr>
<tr>
<th>In Stock: </th>
<td><input type="text"></td>
</tr>
</table>
<input type="text" id="type-field">
<button id="add-item-btn">Add Item</button>