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
[edit | edit source]Elements are removed with the removeChild
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>
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:
<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);
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 elementconstchild=document.getElementById("child");// retrieve the parentconstparent=child.parentNode;// no parenthesis ()// remove the child element from the documentparent.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
<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.