Native Javascript Ninjutsu: removeNode vs. removeChild

Ninja kanji

Sensei Says (dark ages, to dojos, to disciplines)

Javascript used to be a dark and ancient art, looked down upon by many web developers as a dishonorable – even malicious – ‘copy and paste’ language. Macromedia’s Shockwave – which later became Macromedia Flash, which even later became Adobe Flash – pushed audio, video, and interactive motion graphics onto the web in a cross-browser compatible format that all but decimated the need and appeal for Javascript. What little Javascript community there was began to seriously dwindle and die out.

And then the frameworks came to rise: Dojo, Yahoo! UI Library, Google Web Toolkit, jQuery, Prototype, MooTools, and many more. With these powerful armies by its side, the Javascript community quickly grew and regained its honor, competing heavily with the fluid animation and complex, real-time interactivity that Flash had delivered for years.

Javascript now seems to be a strong, healthy, and widely accepted language, frequently used and relied upon by web developers across the land. Yet how many of today’s programmers can write pure native Javascript without the aid of a framework? How many can perform AJAX requests without a framework? And most importantly, how many can craft fully cross-browser compatible code without a framework? In order to not become dependent on the frameworks – and thus risk sliding backwards into the dark ages – we must maintain a wide variety of practices: these are the native Javascript disciplines.

Discipline 5: Intonjutsu (escaping and concealment)

Recently there have been a few occasions in which I needed to remove element nodes from the DOM. In some cases the HTML layout needed to be restructured and in other cases I’ve been asked to make sure that various script tags were removed after their contents had been executed. Learning how to remove element nodes from the DOM can be very useful for a variety of reasons.

The most straightforward way to remove an HTML element is by using its id attribute to select it and then applying the removeNode() method to remove it from the DOM:

[js]
document.getElementById( ‘the_element_id’ ).removeNode( true );
[/js]

Apparently you must pass the true parameter to the removeNode() method in order for it to work properly. In theory, this will work, but be aware that if the element you are trying to select does not exist then the JS will throw an error and cease execution immediately. This means that any following JS code will not be processed. In order to avoid this you’ll want to check if the element actually exists before attempting to remove it:

[js]
var the_element = document.getElementById( ‘the_element_id’ );

if ( the_element !== null )
{
the_element.removeNode( true );
}
[/js]

There is one major problem with this approach; it’s not cross-browser compatible at all. In my tests the removeNode() method only worked in IE and Opera, failing in FF, Google Chrome, and Safari. Due to this unfortunate lack of support we’re forced to rely on the removeChild() method:

[js]
var the_element = document.getElementById( ‘the_element_id’ );

if ( the_element !== null )
{
the_element.parentNode.removeChild( the_element );
}
[/js]

The above JS code begins by attempting to select the element by the given id value, storing the results to the_element variable. The code then checks this variable to see if the element actually exists or not. This is important to do because if you try to remove an element that does not exist your code will fail and any following JS will not be executed (as I’ve already explained above). If the element does exist then we must first select it’s parent node by using the parentNode() method, after which we can then remove the element itself by applying the removeChild() method and passing it the_element as a parameter. I know this may seem a bit convoluted, but this is the simplest – and most straightforward – way to remove an HTML element using purely native and fully cross-browser compatible JS.

I mentioned in the beginning of this tutorial that I’m sometimes asked to make sure all included JS code is removed from the HTML DOM as soon as it’s finished being executed. I accomplish this by storing the id attribute values of the script elements into a JS array and then passing this array to a for loop which removes them one by one:

[js]
var script_ids = [ 'first_script_id', 'second_script_id', 'third_script_id' ];

script_ids.reverse();

for ( var index in script_ids )
{
var the_script = document.getElementById( script_ids[index] );

if ( the_script !== null )
{
the_script.parentNode.removeChild( the_script );
}
}
[/js]

You’ll notice that I use the reverse() method on the script_ids array so that it starts from the last script. I do this because I want to remove them in the reverse order they were added. To further explain, I normally store the removal code in a globally accessible function which is defined in the first script I include. For this reason, the first script needs to be the last one I remove or the removal function well no longer be accessible (and thus the scripts won’t all be removed properly). Here’s a fuller, working example of this process:

[html]
<html>
<head>
</head>
<body onload="remove_all_scripts();">

<script type="text/javascript" id="first_script_id">
var script_ids = [ 'first_script_id' ];

function remove_script ( script_id )
{
var the_script = document.getElementById( script_id );

if ( the_script !== null )
{
the_script.parentNode.removeChild( the_script );
}
}

function remove_all_scripts ()
{
script_ids.reverse();

for ( var index in script_ids )
{
remove_script( script_ids[index] );
}
}
</script>

<script type="text/javascript" id="second_script_id">
script_ids.push( ‘second_script_id’ );
</script>

<script type="text/javascript" id="third_script_id">
script_ids.push( ‘third_script_id’ );
</script>

</body>
</html>
[/html]

It should be pretty clear what I’m doing in the above example. It’s important to note that you should wait until the DOM is fully loaded before you actually call the remove_all_scripts() method or you may run into serious trouble attempting to remove a node that only half exists! This is the reason why I’m relying on the onload attribute of the body element. You might also pay close attention to the fact that I’m using the push() method to add each script’s id to the script_ids array. I’m making sure this happens only once the respective script has actually been added to the page (if you imagine that some of these scripts might be dynamically added then this should begin to make a lot more sense). Alternatively you could specify the list of script ids that you presume to load, but to me it seems much cleaner and more elegant to do it like this.

I hope this tutorial has been helpful in providing you with a way to use native JS to remove HTML elements from the DOM. Stay tuned for next week’s discipline: DOMinating iframes.

Previous Disciplines
Discipline 1: AJAX with XHR
Discipline 2: Dynamic JS with PHP
Discipline 3: Include External JS
Discipline 4: Cookies and Variables

Are you smart? Innovative? Driven? If you’re interested in working on challenging projects in one of the world’s most fast-paced industries, why not check out the openings on our Careers page?

Back to news overview