Volleynerd Knowledge Base

Monday, August 01, 2005

Firefox DOM Differences


Where have I been? I guess just following the IE non-compliant train...

I came across the first non-conforming piece of DHTML today when trying to update the innerText of an element. As I've been doing for my whole life with IE, I was trying

someElement.innerText = 'whatever';

That doesn't do anything in Firefox. So I tried to narrow it down. When you alert( someElement ), it works, gives you back an HTMLSpanElement, but what to do from there is the trick.

Thanks to Google Groups, some dudes were talking about w3c compliant firstChild DOM property ...

So here's the Firefox (and IE) compatible code:

someElement.firstChild.data = 'whatever';

Here's the formal reference for the Node interface in the object model.



Follow-up note: if the SPAN element starts off empty, the firstChild property will be null.

In other words, an element only has children if there is text (or other elements) below it in the DOM hierarchy.

Quick fix for now, I started the SPAN tag with a space. (IE will ignore a true space, so use   )



If you want to do this the RIGHT way...look for child node, if not there, add it, otherwise, alter the existing node. Like so:
if ( dan.firstChild == null )
{
node = document.createTextNode( 'added it' );
dan.appendChild( node );
}
else
dan.firstChild.data = 'replaced it';
See reference above for info on the createTextNode and createElement methods.



Comments: Post a Comment

Home