Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Very strange error caused by html whitespace

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?

like image 847
YsoL8 Avatar asked Jul 04 '11 13:07

YsoL8


1 Answers

It is not a bug. The DOM has not only element nodes, but also text nodes [docs] (among others). In this example:

<div>
<p>Q: Where's the rabbit?</p>

you have at least two text nodes:

  • One between the <div> and the <p>, containing a line-break.
  • One text node inside the <p> element node, containing the text Where's the rabbit?.

Thus, if elementsList[i].parentNode refers to the <div> element,

elementsList[i].parentNode.firstChild

will refer to the first text node.

If you want to get the first element node, use

elementsList[i].parentNode.children[0]

Update: You mentioned Firefox 3.0, and indeed, the children property 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:

var firstChild = elementsList[i].parentNode.firstChild;

// a somehow shorthand loop
while(firstChild.nodeType !== 1 && (firstChild = firstChild.nextSibling));

if(firstChild) {
    // exists and found
}

You might want to put this in an extra function:

function getFirstElementChild(element) {
    var firstChild = null;
    if(element.children) {
        firstChild = element.children[0] || null;
    }
    else {
      firstChild = element.firstChild;
      while(firstChild.nodeType !== 1 && (firstChild = firstChild.nextSibling));
    }
    return firstChild;
}

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:

$('.faq_answer').prev().append(finalRender.cloneNode(true));

(assuming the p element always comes before the .faq_answer element)

This is the whole code, you wouldn't have to loop over the elements anymore.

like image 195
Felix Kling Avatar answered Nov 15 '22 10:11

Felix Kling