I'm Dudley Storey, the author of Pro CSS3 Animation. This is my blog, where I talk about web design and development with HTML, CSS and SVG. To receive more information, including news, updates, and tips, you should follow me on Twitter or add me on Google+.

my books

Pro CSS3 Animation book coverPro CSS3 Animation, Apress, 2013

my other blogs

Massive Head CanonMassive Head Canon: Intelligent discussion of movies, books, games, and technology.

my projects

The New DefaultsThe New Defaults — A Sass color keyword system for designers.

CSSslidyCSSslidy — an auto-generated #RWD image slider. 3.8K of JS, no JQuery.

Removing Elements With JavaScript

Cutting and pasting in JS.

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.

This site helps millions of visitors while remaining ad-free. For less than the price of a cup of coffee, you can help pay for bandwidth and server costs while encouraging further articles.