development blog for the wicked stuff we encounter

Possibly every web developer in his/her lifetime faces with a common DOM error: in IE/Opera the getAttribute() function works as expected for a given item, but in Firefox it misteriously somehow says it's not a function, or the direct reference to the node object's attributes returns undefined value. The problem is, that Firefox's DOM handling generally differs from IE's MSXML DOM method. Basically, in Firefox every node has more nodes as it seems. For example see the following sniplet: <div id="first"><a href="http://skaelede.hu">text</a></div> if you want to query the href attribute of the a node, you'd say: document.getElementById("first").childNodes[0].getAttribute('href') in IE, it works flawlessly, but FF will break completely! Why? Because as it seems, the "a" node is the only child of the div, but in reallity, it is not. Let's face it: we forgot one element: the div text itself, what is currently empty! This will be the first node, and of course it can't have any attributes. To work around this problem, first we should loop through all childs in this simple nodeset as well. In step 2, we need to look up the given childNode's nodeType, if it's a suitable element node: var l = document.getElementById("first"); if (l.hasChildNodes()) { for (i=0;i<l.childNodes.length;i++) { var m = l.childNodes[i]; if (m.nodeType == 1) { var n = m.getAttribute('href'); } }