There are two methods of removing elements from web pages with JavaScript: the traditional, counter-intuitive way, and the new direct DOM4 method.
The traditional method is rather round-about: you cannot simply remove an element, but must do so via a reference to its parent. Given the following markup:
<div id="leftcol">
<h1>Yggdrasil Explorer</h1>
<nav> </nav>
<p id="description"> Yggdrasil is the "WorldTree" of Norse mythology, a cosmos-spanning ash that connects the nine worlds.
</div>
<div id="norsemap"> </div>
If I wanted to remove description
from the DOM, I could do the following.
var description = document.getElementById("description");
description.parentNode.removeChild(description);
This method is bizarrely self-reflective, but it has the advantage of working in every browser. Visually, it has the same effect as setting description
to display: none
in CSS, but of course the element is completely removed from the DOM, not merely hidden.
The removed element remains as a reference in JavaScript, floating in memory: if I wanted to attach the removed description
to the norsemap
element, I could do the following:
var norsemap = document.getElementById("norsemap");
norsemap.appendChild(description);
An upcoming article will explore more possibilities of this “cut and paste” ability of JavaScript, particularly in how it can be used in responsive design.
.remove()
DOM4 provides a far more direct method. Returning to the original code, we can simply use:
var description = document.getElementById("description");
description.remove();
Great, right? There’s just one problem: the method only works on recent browsers (Chrome & Firefox 23+, Opera 10+, and Safari 7+), and not at all in Internet Explorer… not even IE11, at least as of this writing. However, polyfills exist, such as DOM4 & DOMShim.
Photograph by Nomadic Lass, licensed under Creative Commons.
Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.