How to remove the parent element using plain Javascript

前端 未结 9 882
一生所求
一生所求 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:50

    Simple function to do this with ES6:

    const removeImgWrap = () => {
        const wrappedImgs = [...document.querySelectorAll('p img')];
        wrappedImgs.forEach(w => w.parentElement.style.marginBottom = 0);
    };
    
    0 讨论(0)
  • 2020-12-03 04:52

    I know it's a little too late, but someone else might find it useful.
    Just wrote a function for that.

    Change this:

    onClick="delete_row(this)"
    

    To this:

    onClick="removeParents(this, document.getElementById('id'))"
    

    function removeParents(e, root) {
        root = root ? root : document.body;
        var p = e.parentNode;
        while(root != p){
            e = p;
            p = e.parentNode;
        }
        root.removeChild(e);
    }
    

    http://jsfiddle.net/emg0xcre/

    0 讨论(0)
  • 2020-12-03 05:06

    I know I am too late but I still can't see more accurate answer.

    So here you go.

    You can specify it even more. Instead of parentElement.parentElement you can do something like this.

    static delete_row(element) { 
       element.closest("tr").remove();
    }
    

    The other preferred way of handling such scenario would be event propagation instead of adding onclick to html element.

    e.g

    HTML

    <tr id='id'>
       <td>Mohit</td>   
       <td>23</td>
       <td > 
          <span class="edit">Edit</span> | 
          <span class="delete">Delete</span>
       </td>   
       <td style="display:none;"><span onClick="save(this)">Save</span></td>   
    </tr>
    

    JavaScript

     document.querySelector("#id").addEventListener("click", (e) => {
       UI.handleEvents(e.target);
     });
    
     static handleEvents(el){
    
       if (el.classList.contains("delete")) {
         el.closest("tr").remove();
       }
    
       if (el.classList.contains("edit")) {
         // do something else
       } 
    
     }
    
    0 讨论(0)
提交回复
热议问题