Element removal with Javascript

8

Removing an element using Jquery is the simplest and most objective thing to do, first you capture the element and then remove it:

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

I came in a situation where I need to remove the element only with pure javascript, but from what I understand, it is necessary to capture the node of the parent element to later remove the target element:

var elemento = document.getElementById("elemento");
elemento.parentNode.removeChild(elemento);

I can not understand the reason for doing this, not even understand how this code is working.

1- How does this code work?

2 - What is the reason why javascript needs to go to the parent node first and then remove the element?

3 - Because with jquery is it simple to perform the removal?

    
asked by anonymous 27.09.2018 / 23:30

1 answer

4

As the name of the method itself suggests, remove child ), it needs a parent element to fetch a child, and must be a child direct , otherwise it returns in error.

But you can remove the element directly without needing a parent using the removeChild() method:

document.getElementById("id-do-elemento").remove();

Or remove() :

document.getElementById("id-do-elemento").outerHTML = '';
  

According to Can I Use , outerHTML is not compatible with Internet Explorer.

jQuery

jQuery is just a library that aims to simplify the use of JavaScript. In most cases, a simple line of code in jQuery does what you would do with some lines in pure JavaScript, but this feature comes at a price: it's slower because it's an intermediary, and you need to load the library on the page. >     

28.09.2018 / 00:16