HTML pages and DOM objects are hierarchically structured. Every element and attribute belongs to exactlyone parent. To delete an element or attribute, first, you must locate the parent element. The remove operation can be done on this object.
Elements are removed with theremoveChild function. To delete the<p> element from the<div> element in the following example
<divid="parent"><pid="child">I'm a child!</p></div>
the JavaScript code is ...
// get elementsconstparent=document.getElementById("parent");constchild=document.getElementById("child");// delete childparent.removeChild(child);
... and the remaining HTML structure will be
<divid="parent"></div>
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:
<divid="div_1"><ulid="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.
constparent=document.getElementById("div_1");constchild=document.getElementById("listOfNames");parent.removeChild(child);
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 propertyparentNode shows you the way.
// get the child elementconstchild=document.getElementById("child");// retrieve the parentconstparent=child.parentNode;// no parenthesis ()// remove the child element from the documentparent.removeChild(child);
Attributes are removed with theremoveAttribute function. To delete thehref attribute from the<a> element in the following example
<aid="anchor"href="https://en.wikibooks.org">Wikibook</a>
the JavaScript code is:
// get elementconstanchor=document.getElementById("anchor");// remove attributeanchor.removeAttribute("href");
The element itself, including the text of the link, keeps alive, but you cannot navigate anymore.