Currently, I am working on a project that involves adding and removing items as needed. The user interface can be seen in the image provided below:
https://i.sstatic.net/Qhy2t.png
Workflow: When the add icon is clicked, a new column is added for assignment purposes. Similarly, clicking the delete icon marked "x" removes a column from the list. These functionalities are all working correctly - columns can be successfully added and removed.
Issue: However, an error occurs when trying to remove a column that was previously added using the add button. For example, if there were originally two columns and a third one was added through the add button, attempting to remove that third column triggers an error.
Error Message: Logic.js:238 Uncaught DOMException: Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node. at HTMLElement.
Code Snippet:
/**
* A helper function for retrieving DOM elements
* @param {any} elem
* @returns
*/
const getElements = (elem) => {
const deleteBtns = Array.from(elem.getElementsByClassName("delete-btn"));
const permissions = elem.getElementsByClassName("permissions-row") || elem
const elements = {
row: permissions,
button: deleteBtns
}
return elements;
}
/*** Creates new permissions for the permission edit modal ****/
const addColumns = (elem) => {
elem.querySelector(".add-permission").addEventListener("click", () => {
const permsRow = getElements(elem).row
const col = elem.querySelector(".col-6").cloneNode(true)
console.log(permsRow[0])
permsRow[0].appendChild(col);
deleteColumns(permsRow[0])
} )
}
/**
* Deletes permissions from the permissions edit modal
*/
const deleteColumns = (elem) => {
const deleteBtns = getElements(elem).button;
const permissions = getElements(elem).row;
deleteBtns.forEach(btn => {
btn.addEventListener("click", (event) => {
updatePermissions(elem);
const currentPermission = event.target.parentNode.parentNode
Swal.fire({
icon: 'question',
title: 'Delete',
text: 'Do you want to delete this permission?!',
})
console.log(permissions);
if (deleteBtns.length === 1) return;
if (permissions.length === 0) {
console.log(deleteBtns.length)
elem.removeChild(currentPermission)
} else {
permissions[0].removeChild(currentPermission);
}
})
})
}
I would greatly appreciate any insights or suggestions on why I am encountering the aforementioned error in the console.
Thank you!
I have attempted parsing the cloned nodes and utilized helper functions, but unfortunately, the issue persists.