Akatombo Web Log
Wednesday, June 21, 2006
The hazards of self-taught Dom Scripting
I just had one of the epiphanies so common in the life of a self-taught programmer. These types of epiphanies seem to be much more common for me in Javascript than in other programming languages. I’m talking, of course, of those moments when you realize that there is a much better and/or more intuitive way of doing something that you’ve always thought was really inconvenient, but had just accepted as the only way to do it. People familiar with the technique you’ve discovered will be shocked that anyone could ever even have considered doing it the way you’ve done it, and you feel like an idiot.
Well, just in case there is anyone else out there who has been doing things the way I have been, I’m revealing my idiocy to the world. I’m still relatively unskilled when it comes to dom scripting so if any of you have any tips, please let me know. And now on to my embarrassing lack of knowledge:
Probably one of the most common I do in dom scripting is adding and removing elements to the dom tree (client side form validation and things like that). Adding elements has been no problem though it often seems like I’m going through contortions to specify where to add things. Removing things has always seemed wrong. The only way I knew to clear an element was to set innerHTML to an empty string.
targetElement.innerHTML = “”;
If you are familiar with innerHTML you’ll know that doing something that doesn’t actually remove the element, it just removes everything inside it. So if the element you want to remove is alone inside a parent node you can remove the offending element altogether, but in a situation like:
<div><h2>the offending element</h2><p>Content we want to keep</p></div>
It it impossible to just remove the h2 element and leave the p tag in tact. The best you can do it to remove the contents of the h2 element and end up with something like:
<div><h2></h2><p>Content we want to keep</p></div>
Which is not at all what we want. I also knew of removeChild, which was fine when I could identify the both the parent of the node I wanted to remove, and the node I wanted to remove. I also knew of parentNode, but somehow in the muddled swamp that is my brain the two concepts never found each other until today when I realized I can do this:
toClear = getElementById(’error’);
toClear.parentNode.removeChild(toClear);
Rereading this, I feel like I was way too excited about it, but it hit me like a bolt of lightning and made my life quite a bit easier today. I hope it helps somebody else out somewhere down the line.
Page 1 of 1 pages

