Jump to content

JavaScript/Removing elements

From Wikibooks, open books for an open world



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

[edit | edit source]

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>
</div>

the JavaScript code is ...

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

// delete child
parent.removeChild(child);

... and the remaining HTML structure will be

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

Children of children

[edit | edit source]

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">
    <li>Albert</li>
    <li>Betty</li>
    <li>Charles</li>
  </ul>
</div>

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

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

parentNode

[edit | edit source]

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
parent.removeChild(child);

Remove attributes

[edit | edit source]

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

<a id="anchor" href="https://en.wikibooks.org">Wikibook</a>

the JavaScript code is:

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

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

See also

[edit | edit source]