Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - Remove dom element without knowing its parent?

Is it possible to remove a dom element that has no parent other than the body tag? I know this would be easy with a framework like jquery, but I'm trying to stick to straight javascript.

Here's the code I've found to do it otherwise:

function removeElement(parentDiv, childDiv){
     if (childDiv == parentDiv) {
          alert("The parent div cannot be removed.");
     }
     else if (document.getElementById(childDiv)) {     
          var child = document.getElementById(childDiv);
          var parent = document.getElementById(parentDiv);
          parent.removeChild(child);
     }
     else {
          alert("Child div has already been removed or does not exist.");
          return false;
     }
}   

Thanks!

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

You should be able to get the parent of the element, then remove the element from that

function removeElement(el) {
el.parentNode.removeChild(el);
}

Update

You can set this as a new method on the HTMLElement:

HTMLElement.prototype.remove = function() { this.parentNode.removeChild(this); return this; }

And then do el.remove() (which will also return the element)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...