How do I remove the parent element and all the respective nodes using plain JavaScript? I'm not using jQuery or any other library. In other words, I have an element and when user clicks on it, I want to remove the parent of the parent element (as well as the respective children nodes).
<table id='table'> <tr id='id'> <td> Mohit </td> <td> 23 </td> <td > <span onClick="edit(this)">Edit</span>/<span onClick="delete_row(this)">Delete</span> </td> <td style="display:none;"> <span onClick="save(this)">Save</span> </td> </tr> </table>
Now,
function delete_row(e) { e.parentNode.parentNode.removeChild(e.parentNode); }
Will remove only last <td>
.
How do I remove the <tr>
directly>?
e.parentNode.parentNode.getAttribute('id')
returns the id of the row...
Is there any function like remove()
or delete()
?
In JavaScript, an element can only be deleted from its parent. To delete one, you have to get the element, find its parent, and delete it using the removeChild method.
To remove an existing HTML element removeChild() must be used. It removes any element from the parent element.
To remove an element from the DOM, you can also use the remove() method of the element. How it works. First, select the last element of the ul element. Second, call the remove() of that element to remove it from the DOM.
removeChild() The removeChild() method of the Node interface removes a child node from the DOM and returns the removed node. Note: As long as a reference is kept on the removed child, it still exists in memory, but is no longer part of the DOM. It can still be reused later in the code.
Change your function like this:
function delete_row(e) { e.parentNode.parentNode.parentNode.removeChild(e.parentNode.parentNode); }
You can now use node.remove()
to remove the whole element so in your case you'd do
function delete_row(e) { e.parentElement.remove(); }
You can read more on it here https://developer.mozilla.org/en-US/docs/Web/API/ChildNode/remove
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With