Advertisement
Advertisement


Remove element by id


Question

When removing an element with standard JavaScript, you must go to its parent first:

var element = document.getElementById("element-id");
element.parentNode.removeChild(element);

Having to go to the parent node first seems a bit odd to me, is there a reason JavaScript works like this?

2020/06/12
1
1154
6/12/2020 10:05:18 AM

Accepted Answer

The DOM is organized in a tree of nodes, where each node has a value, along with a list of references to its child nodes. So element.parentNode.removeChild(element) mimics exactly what is happening internally: First you go the parent node, then remove the reference to the child node.

As of DOM4, a helper function is provided to do the same thing: element.remove(). This works in 87% of browsers (as of 2016), but not IE 11. If you need to support older browsers, you can:

2020/08/28
82
8/28/2020 10:53:09 PM


Crossbrowser and IE >= 11:

document.getElementById("element-id").outerHTML = "";
2018/05/14

You could make a remove function so that you wouldn't have to think about it every time:

function removeElement(id) {
    var elem = document.getElementById(id);
    return elem.parentNode.removeChild(elem);
}
2018/04/19

It's what the DOM supports. Search that page for "remove" or "delete" and removeChild is the only one that removes a node.

2018/08/20

For removing one element:

 var elem = document.getElementById("yourid");
 elem.parentElement.removeChild(elem);

For removing all the elements with for example a certain class name:

 var list = document.getElementsByClassName("yourclassname");
 for(var i = list.length - 1; 0 <= i; i--)
 if(list[i] && list[i].parentElement)
 list[i].parentElement.removeChild(list[i]);
2015/03/19

you can just use element.remove()

2014/02/28

Source: https://stackoverflow.com/questions/3387427
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]