Remove a child node from its parent node in real-time

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.

Answer №1

When dealing with the event.target, it's important to note that the node may vary (for instance,

<button><span>x</span></button>
could refer to either the button or the span). Instead of always moving up a fixed two levels using
event.target.parentNode.parentNode
, consider targeting the intended node directly with event.target.closest('.col-6'). This method will locate the nearest ancestor that matches the specified selector.

https://developer.mozilla.org/en-US/docs/Web/API/Element/closest

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The added class is not being successfully applied to the ClassList

I'm currently working on a page where I want the colors of a button and the background to switch when the button is clicked. document.querySelector("body.light").classList.toggle("dark"); document.querySelector("button.dark").classList.toggle("light" ...

What is the reason behind the animation being refreshed when using slideToggle() in jQuery?

Recently, I managed to position a fixed div at the bottom of the viewport to serve as a contact tab. When this tab is clicked, it smoothly triggers a panel to slide out, which is functioning correctly. However, I'm faced with the challenge of making ...

What is the ternary operation syntax for setting the img src attribute in Angular 8?

My data includes a property called "photo" which can either have a file name or be empty. For instance, it could be "steve.jpg" or just an empty string if Steve does not have a photo. In React JSX, I know how to use a ternary operator with the "photo" va ...

Achieving the perfect alignment: Centering a paragraph containing an image using JQuery

I need help centering the background image of my <p> tag on the webpage. Script $(function() { $('ul.nav a').bind('click', function(event) { var $anchor = $(this); $('html, body').stop().animate({ ...

Error Encountered While Serializing Products in getServerSideProps in Next.js v14

I am using Next.js version 14.2.3 and I am currently trying to retrieve a list of products from Firestore by utilizing the getProducts function from @stripe/firestore-stripe-payments within getServerSideProps. However, I am facing a serialization error: ...

The Bootstrap navigation pills do not function properly when using a forward slash in the tab link

I am currently working with Bootstrap and using nav pills. I have noticed that if I include a / sign in the link of a tab, it causes that specific tab to malfunction and triggers a JavaScript error in jQuery's own code when clicked on. How can I go ab ...

A guide on updating the SQL order value through a select option using PHP and jQuery

To modify the arrangement of SQL data according to the chosen select option, I am looking to adjust the ORDER value. Within my action.php file, I retrieve values from the database and aim to incorporate a sorting select option that allows for changing the ...

Implementing a color filter on a camera using Three.js

Can a parameter be adjusted for the camera or renderer to apply a tint to everything on the stage, such as a red shade resembling a "glasses effect", without having to manually modify each object's materials? ...

Guide to aligning a container to the left in Bootstrap 5

I have a grid container in Bootstrap 5 and I'd like to align it to the left on my webpage. <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3f5d50504b4c4b4b54e42f56b61a0acf40"&g ...

What is the best way to locate a particular JSON key value pair through JavaScript?

I'm in the process of creating a unique app that forecasts the weather for an upcoming event based on the city location specified. To achieve this, I am utilizing two APIs - one API provides an array of objects representing each event by an artist ent ...

AngularJS tip: monitor the size of a filter in ng-repeat loop

Take this example of a repeated list: <ul> <li class="suggestion-item" ng-repeat="item in suggestionList.items | filter: {id: 2} track by track(item)">{{item.text}}</li> <ul> Is there a way to check if the filter results are n ...

Insert the <span> element within the <a> element with the help of Jquery

I am attempting to insert a span tag inside .block-leftnav ul li .parent a, however, instead of adding the tag after only the .parent a, jQuery is adding the span tag after every href tag on my page. Below is the code I am using to achieve my desired outc ...

What could be causing this code to malfunction on jsfiddle?

Why doesn't this code from W3schools work on jsfiddle? I tried to implement it here: https://jsfiddle.net/u6qdfw5f/ <!DOCTYPE html> <html> <title>W3.CSS</title> <meta name="viewport" content="width=device-width, initial ...

What is the best way to have a text field automatically insert a hyphen after specific numbers?

Is there a way to make a text field insert hyphens automatically after certain numbers? For example, when typing a date like 20120212, could we have the input automatically formatted with hyphens after the first 4 digits and the second two, so it displays ...

Is it necessary to exclude the 'scripts' folder from your Aurelia project's .gitignore file?

Should I exclude the 'scripts' directory that Aurelia is building to in my CLI project from Git by adding it to .gitignore, or is there a specific purpose for tracking changes to this directory? ...

Bootstrap 5.3.0 - Navigation bar on index.html mysteriously expands without collapsing

I'm currently working on creating a responsive navigation bar. I have encountered an issue where clicking the hamburger button expands the navigation bar, but clicking it again does not collapse it. Despite trying various solutions that I found online ...

Troubleshooting: Issue with AJAX xmlhttp.send() functionality

I'm new to AJAX and have been stuck on the same issue for hours. Here is my script code: <script language='javascript'> function upvote(id ,username) { var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = fun ...

Guide on displaying JSON data from a server on a webpage using Google Charts in real-time

Although I am not a JavaScript developer or an expert in AJAX, I consider myself a novice desktop developer. I would greatly appreciate it if you could guide me on how to connect an MCU that returns JSON data to a web page using Google gauge, running on th ...

When placed in a conditional, the type of the body variable changes from a string to undefined

Unexpectedly, the final if block fails to retain the value of the body variable and transforms it into undefined. While the console log statement just before the block correctly displays the type of the variable as a "string", during the condition check an ...

The proper method for redirecting the view after a successful AJAX request in a MVC application

Explanation of the Issue: I have added a search function to the header section of my MVC website. It includes an input text box and a 'Search' button. The Problem at Hand: Currently, I have incorporated an AJAX function in the shared master la ...