I have encountered a very strange bug in Firefox.
I have a javascript function in an external file that works perfectly on regular complexity websites. However I have been putting together a few demonstration examples and come across something odd.
With html formatted like this (in an editor):
<div><p>Q: Where's the rabbit?</p><p class="faq_answer">A: I don't know, honest</p></div>
The Javascript works as expected.
However when like this:
<div>
<p>Q: Where's the rabbit?</p>
<p class="faq_answer">A: I don't know, honest</p>
</div>
It fails at this line:
elementsList[i].parentNode.firstChild.appendChild(finalRender.cloneNode(true));
Why on Earth would formatting of html cause anything at all?
It is not a bug. The DOM has not only element nodes, but also text nodes [docs] (among others). In this example:
you have at least two text nodes:
<div>and the<p>, containing a line-break.<p>element node, containing the textWhere's the rabbit?.Thus, if
elementsList[i].parentNoderefers to the<div>element,will refer to the first text node.
If you want to get the first element node, use
Update: You mentioned Firefox 3.0, and indeed, the
childrenproperty is not supported in this version.Afaik the only solution to this is to loop over the children (or traversing them) and test whether it is a text node or not:
You might want to put this in an extra function:
You can (and should) also consider using a library that abstracts from all that, like jQuery.
It depends on what your code is actually doing, but if you run this method for every node, it would be something like:
(assuming the
pelement always comes before the.faq_answerelement)This is the whole code, you wouldn’t have to loop over the elements anymore.