JavaScript/Removing elements

HTML pages and DOM objects are hierarchically structured. Every element and attribute belongs to exactly one parent. To delete an element or attribute, first, you must locate the parent element. The remove operation can be done on this object.

Remove elements


Elements are removed with the removeChild function. To delete the <p> element from the <div> element in the following example

<div id="parent">
  <p id="child">I'm a child!</p>

the JavaScript code is ...

// get elements
const parent = document.getElementById("parent");
const child = document.getElementById("child");

// delete child

... and the remaining HTML structure will be

<div id="parent"></div>

Children of children


If an element is removed, all of its children are removed as well. By this, you can remove huge parts of the DOM with one command if they have a common root. E.g., remove a complete list:

<div id="div_1">
  <ul id="listOfNames">

The JavaScript fragment removes the <ul> element as well as all <li> elements.

const parent = document.getElementById("div_1");
const child = document.getElementById("listOfNames");



To remove an element, you need to know its parent element. If you can locate only the child, but for some reason, not the parent, the child's property parentNode shows you the way.

// get the child element
const child = document.getElementById("child");

// retrieve the parent
const parent = child.parentNode; // no parenthesis ()

// remove the child element from the document

Remove attributes


Attributes are removed with the removeAttribute function. To delete the href attribute from the <a> element in the following example

<a id="anchor" href="">Wikibook</a>

the JavaScript code is:

// get element
const anchor = document.getElementById("anchor");
// remove attribute

The element itself, including the text of the link, keeps alive, but you cannot navigate anymore.

See also