Very strange error caused by html space

I encountered a very strange error in Firefox.

I have a javascript function in an external file that works fine on regular complexity websites. However, I gathered some demos and met something strange.

With html formatted like this (in the editor):

<div><p>Q: Where the rabbit?</p><p class="faq_answer">A: I don't know, honest</p></div>

Javascript works as expected.

However, if:

<div>
<p>Q: Where the rabbit?</p>
<p class="faq_answer">A: I don't know, honest</p>
</div>

This line fails:

elementsList[i].parentNode.firstChild.appendChild(finalRender.cloneNode(true));

Why on earth does html formatting cause anything at all?

+5
source share
3 answers

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

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

:

  • <div> <p>, .
  • node <p> node, Where the rabbit?.

, elementsList[i].parentNode <div>,

elementsList[i].parentNode.firstChild

node.

node,

elementsList[i].parentNode.children[0]

: Firefox 3.0, , children .

Afaik ( ) , node :

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

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

if(firstChild) {
    // exists and found
}

, :

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;
}

( ) , , jQuery.

, , node, :

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

(, p .faq_answer)

, .

+7

node <div> <p>.

, : !

+2
0