Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
274 views
in Technique[技术] by (71.8m points)

javascript - Remove an element from the DOM from reference to element only

This is either very simple or impossible.

I know I can do this:

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

...but it feels messy. Is there a tidier - and universally supported - way to do the same thing?

It's seems - to me at least - like there should be something like this:

document.getElementById('some_element').remove();

...but that doesn't work, and searching Google/SO has not yielded any alternative.

I know it doesn't matter that much, but parentNode.removeChild() just feels hacky/messy/inefficient/bad practice-y.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...