Akatombo Web Log
Wednesday, June 21, 2006
The hazards of self-taught Dom Scripting
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’);
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