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
editElements 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
editIf 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
editTo 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
editAttributes 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.