Remove an element from the DOM from reference to element only

后端 未结 3 1669
醉梦人生
醉梦人生 2020-12-01 10:50

This is either very simple or impossible.

I know I can do this:

var element = document.getElementById(\'some_element\');
element.parentNode.removeChi         


        
相关标签:
3条回答
  • Your code is the correct and best way to do it.

    jQuery has what you're looking for:

    $("#someId").remove();
    
    0 讨论(0)
  • 2020-12-01 11:52

    The DOM level 4 specs seems to have adopted the "jQuery philosophy" of doing several DOM changing operations (see https://dvcs.w3.org/hg/domcore/raw-file/tip/Overview.html#interface-element). Remove is one of them:

    var el = document.getElementById("myEl");
    el.remove();
    

    At this time, it's only supported in later version of Chrome, Opera, Firefox, but there are shims to patch this up if you want to use this functionality in production today: https://github.com/Raynos/DOM-shim

    Wether it's preferable to removeChild or not, I leave undebated for now.

    0 讨论(0)
  • 2020-12-01 11:57

    It can seem a bit messy, but that is the standard way of removing an element from its parent. The DOM element itself can exist on its own, without a parentNode, so it makes sense that the removeChild method is on the parent.

    IMO a generic .remove() method on the DOM node itself might be misleading, after all, we're not removing the element from existence, just from its parent.

    You can always create your own wrappers for this functionality though. E.g.

    function removeElement(element) {
        element && element.parentNode && element.parentNode.removeChild(element);
    }
    
    // Usage:
    removeElement( document.getElementById('some_element') );
    

    Or, use a DOM library like jQuery which provides a bunch of wrappers for you, e.g. in jQuery:

    $('#some_element').remove();
    

    This edit is in response to your comment, in which you inquired about the possibility to extend native DOM implementation. This is considered a bad practice, so what we do instead, is create our own wrappers to contain the elements and then we create whatever methods we want. E.g.

    function CoolElement(element) {
        this.element = element;
    }
    
    CoolElement.prototype = {
        redify: function() {
            this.element.style.color = 'red';
        },
        remove: function() {
            if (this.element.parentNode) {
                this.element.parentNode.removeChild(this.element);
            }
        }
    };
    
    // Usage:
    
    var myElement = new CoolElement( document.getElementById('some_element') );
    
    myElement.redify();
    myElement.remove();
    

    This is, in essence, what jQuery does, although it's a little more advanced because it wraps collections of DOM nodes instead of just an individual element like above.

    0 讨论(0)
提交回复
热议问题