开发者

Why do i get a [Text Object] instead of the expected TR object with previousSibling in javascript?

So if I have HTML code like this:

<HTML>
  <HEAD>
    <TITLE>This is a test</TITLE>
  </HEAD>
  <BODY>
    <TABLE>
      <TR>
        <TD>First Cell</TD>
      </TR>
      <TR>
        <TD>Second Cell</TD>
        <TD><A href="#" oncl开发者_如何转开发ick="alert(this.parentNode.parentNode.previousSibling.childNodes[0].innerHTML); return false;">Click Here</A></TD>
      </TR>
    </TABLE>
  </BODY>
</HTML>

This works for Internet explorer, but not for Firefox and probably more browsers out there. Apparently Firefox interprets the whitespace between the TR's(indentation) as the previousSibling of the parent TR of 'this' in my code above. So instead of getting the desired TR object it gives me a [Text Object].

So my question now is, why doesn't Firefox ignore the whitespace between TR's like Internet Explorer does. I know I can use previousElementSibling to circumvent this, but i want to know why Firefox does this and if there is a logical explanation or a use for it. I've tried looking it up on the internet but to no avail. So if someone could tell me or give me a link where I can find this information, I would appreciate it!


Yes you are correct. It is actually IE that is principally wrong. Here is Mozilla's take on it

You can

a) use parentNode.getElementsByTagName
b) flatten the dom by looping loop until nodeType is what you were looking for: Here is a simpler script than what Mozilla gave in the link above: http://blog.tegneblokken.net/2009/08/counting-childnodes-with-javascript-the-whitespace-incident/
c) use jQuery


Whitespace between elements is significant in HTML and in many situations affects rendering, even in IE, so IE is the weirdo here.

You could write simple functions to mask this difference:

function previousSibling(node) {
    while ( (node = node.previousSibling) && node.nodeType == 3 && /^\s*$/.test(node.data));
    return node;
}

function nextSibling(node) {
    while ( (node = node.nextSibling) && node.nodeType == 3 && /^\s*$/.test(node.data));
    return node;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜