How to remove the parent element using plain Javascript

前端 未结 9 881
一生所求
一生所求 2020-12-03 04:37

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 whe

相关标签:
9条回答
  • 2020-12-03 04:44

    Change your function like this:

    function delete_row(e)
    {
        e.parentNode.parentNode.parentNode.removeChild(e.parentNode.parentNode);
    }
    
    0 讨论(0)
  • 2020-12-03 04:44
    node.parentNode.parentNode.removeChild(node.parentNode)
    

    Edit: You need to to delete parent of parent, so add one more .parentNode

    node.parentNode.parentNode.parentNode.removeChild(node.parentNode.parentNode)
    
    0 讨论(0)
  • 2020-12-03 04:46

    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

    0 讨论(0)
  • 2020-12-03 04:47

    Great question. This worked for me:

     e.target.parentElement.parentElement.parentElement.remove()
    
    0 讨论(0)
  • 2020-12-03 04:48

    Or for those who like a one-liner

    <button onClick="this.parentNode.parentNode.removeChild(this.parentNode);">Delete me</button>
    
    0 讨论(0)
  • 2020-12-03 04:48

    I know it's a little too late, but someone else might find it useful.

     e.target.parentElement.parentElement.parentElement.remove()
    
    0 讨论(0)
提交回复
热议问题