Remove page element with javascript

7

I'm making an application and I had a question:

How can I remove an element from a page with javascript without using innerHTML = '' ?

For example, I want to remove a div (like the example below) and all its contents:

<div id="conteudo">
  <ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
  </ul>
</div>

How could I do this with pure Javascript?

    
asked by anonymous 06.02.2014 / 17:04

3 answers

19

You can use Node.removeChild

Note that to remove the node (and not just the contents of it), you must first retrieve the parent of this node:

// Removendo um nó a partir do pai
var node = document.getElementById("conteudo");
if (node.parentNode) {
  node.parentNode.removeChild(node);
}
    
06.02.2014 / 17:10
5

So:

var el = document.getElementById( 'conteudo' );
el.parentNode.removeChild( el );
    
06.02.2014 / 17:11
1

It's simple:

document.getElementById('conteudo').remove()
    
06.02.2014 / 17:12