Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove the parent element using plain Javascript

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() ?

like image 538
Mohit Jain Avatar asked Apr 28 '10 08:04

Mohit Jain


People also ask

How do you remove an element in JavaScript?

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.

How do you remove an existing element from the parent in HTML?

To remove an existing HTML element removeChild() must be used. It removes any element from the parent element.

How do I completely remove an element from a DOM?

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.

What is removeChild in JavaScript?

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.


2 Answers

Change your function like this:

function delete_row(e) {     e.parentNode.parentNode.parentNode.removeChild(e.parentNode.parentNode); } 
like image 192
Jakob Kruse Avatar answered Oct 17 '22 08:10

Jakob Kruse


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

like image 27
Syed Shamikh Shabbir Avatar answered Oct 17 '22 07:10

Syed Shamikh Shabbir