Remove page element with javascript

Asked

Viewed 44,310 times

14

I’m making an application and I came up with a question:

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

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

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

How could I do this with pure Javascript?

4 answers

28


You can use Node.removeChild

Note that in order to remove the node (and not only the contents of it), you need to first recover the parent of this node:

// Removendo um nó a partir do pai
var node = document.getElementById("conteudo");
if (node.parentNode) {
  node.parentNode.removeChild(node);
}
  • 1

    I put the link to the English version of the Node.removeChild documentation on the Mozilla Developer Network.

  • 1

    What’s the difference between using this code you gave me and this: Document.getElementById('content'). remove() ?

  • 5

    The method removes() NAY is supported by all browsers https://developer.mozilla.org/en-US/docs/Web/API/ChildNode.remove#Browser_compatibility In this list you can see that Internet Explorer and Safari nay support this method. Depending on what your application does and the clients in it, this can cause you many problems in the future.

  • 2

    Thanks for clarifying, I will use this example you suggested and give a study about

6

Thus:

var el = document.getElementById( 'conteudo' );
el.parentNode.removeChild( el );

4

It’s simple:

document.getElementById('conteudo').remove()
  • 1

    That’s right, it worked right, thanks for the help!

  • 2

    No @Odair but I give you a warning: I have tested it now in Internet Explorer and it has no method support .remove

  • 5

    The remove() method is NOT supported by all browsers as you can see here. This list shows that Internet Explorer and Safari do not support this method.

0

You can remove one child element from another with the following code, which in this case was used to remove an element "<button>" who is in "<body>"

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div>oiii</div><!---Esse div é so pra atrapalhar--->
<button>Oláa</button>
<script>
button.addEventListener('click', function(){ 
document.body.removeChild(document.body.querySelector("button"))})
//quando você clicar no botão, o mesmo será deletado
</script>
</body>
</html>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.