Skip to content Skip to sidebar Skip to footer

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

Solution 1:

It is not a bug. The DOM has not only element nodes, but also text nodes (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 loopwhile(firstChild.nodeType !== 1 && (firstChild = firstChild.nextSibling));

if(firstChild) {
    // exists and found
}

You might want to put this in an extra function:

functiongetFirstElementChild(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.

Solution 2:

Because you have a text node between <div> and <p>.

As usual, the assumption of a browser bug is incorrect: this is, instead, a programmer bug!

Solution 3:

Couldn't one achieve it by using ParentNode.children instead?

Post a Comment for "Very Strange Error Caused By Html Whitespace"