Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

element.firstChild is returning '<TextNode ...' instead of an Object in FF

Tags:

I wrote a tab system using some very basic Javascript and it runs like a champ in IE 8 but, in FireFox 3 I am coming up short. The pertitent HTML is as follows:

            <div id="tabs">                 <ul class="tabs">                     <li class="current"><a><span>News</span></a></li>                     <li><a><span>Videos</span></a></li>                     <li><a><span>Photos</span></a></li>                     <li><a><span>Twitter</span></a></li>                 </ul>             </div> 

Then, on page load, I get dropped into this method:

function processTabs(TabContainer, PageContainer, Index) { var tabContainer = document.getElementById(TabContainer); var tabs = tabContainer.firstChild;  var tab = tabs.firstChild; var i = 0; .... more code } 

The rest of the code does not matter at this point because it never gets called. tabContainer is set properly to reference the div with the ID tabs. Now, in Internet Explorer when I call tabContainer.firstChild the variable 'tabs' is referencing my UL and then the call var tab = tabs.firstChild; references my first LI. The problem is that when I call tabContainer.firstChild Venkman is telling me it is returning . So firefox is reading my newlines as actual children inside the div's! My UL is actually the second child in the childNodes collection!

Is there any way to fix this?

Thanks!

like image 483
dparsons Avatar asked Feb 19 '10 21:02

dparsons


2 Answers

You should skip the TextNodes, a simple function can help you:

function getFirstChild(el){   var firstChild = el.firstChild;   while(firstChild != null && firstChild.nodeType == 3){ // skip TextNodes     firstChild = firstChild.nextSibling;   }   return firstChild; } 

Usage:

var tabContainer = document.getElementById(TabContainer); var tabs = getFirstChild(tabContainer); 
like image 144
Christian C. Salvadó Avatar answered Sep 19 '22 17:09

Christian C. Salvadó


You can use node.firstElementChild to ignore leading text, or use a library like jQuery which takes care of this.

like image 35
Max Shawabkeh Avatar answered Sep 19 '22 17:09

Max Shawabkeh