Element removal with Javascript

Asked

Viewed 201 times

8

Remove an element using Jquery is the simplest and most objective thing there is, first you capture the element and then remove it:

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

I arrived 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 then remove the target element:

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

I can’t understand why I’m doing this, nor even understand how this code is working.

1- How this code works?

2 - Why the javascript need to go to the parent node first to then remove the element?

3 - because with the jquery it is so simple to carry out the removal?

  • 2

    1. The code selects the parent element, after that, in the function removeChild, it traverses all child elements to find the element passed via parameter, when the code finds it uses the function remove. 2. Is not the Javascript (in general) that needs to go to the parent node, is the function that requires. You can use element.remove(). 3. Because the jQuery is a library composed of several codes to leave the script easier, though slower.

1 answer

4


As the method name suggests, removeChild() (remove child), he needs a parent element to fetch a child, and he needs to be a direct child, otherwise returns in error.

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

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

Or outerHTML:

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

According to the Can I Use, the .remove() 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 a few lines in pure Javascript, but this facility has a price tag: it’s slower for being an intermediary and you need to load the library to the page.

Browser other questions tagged

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