views:

86

answers:

3

My HTML looks like this:

<html>
<head>
   <title>Test</title>
   <script type="text/javascript" src="jQuery.js"></script>
   <script type="text/javascript">
      function init() 
  {
         var text = jQuery('body').text();
         alert('length = ' + text.length);
      }
   </script>
</head>
<body onload="init()">0123456789</body>
</html>

When I load this in Firefox, the length is reported as 10. However, in Chrome it's 11 because it thinks there's a linefeed after the '9'. In IE it's also 11, but the last character is an escape. Meanwhile, Opera thinks there are 12 characters, with the last two being CR LF.

If I change the body element to include a span:

<body onload="init()"><span>0123456789</span></body>

and the jQuery call to:

var text = jQuery('body span').text();

then all the browsers agree that the length is 10.

Clearly it's the body element that's causing the issue, but can anyone explain exactly why this is happening? I'm particularly surprised because the excellent jQuery is normally browser-independent.

A: 

Shocking that different browsers would behave in different ways...

Might I suggest:

jQuery('iframe').contents().find('body').text().trim();

I expect you will then get the same result.

Hogan
Good idea, and it works in this case. However, what if I meant there to be whitespace at the end?
Charles Anderson
Note that the example code in this answer was in response to an earlier version of this question, but the suggestion still stands.
Charles Anderson
A: 

Some of this may have to do with different behavior for where browsers put the text that's outside body but inside HTML, or the text that's outside of HTML. It wouldn't surprise me if that's changed in Firefox nightlies since the HTML5 parser landed.

David Baron
+1  A: 

Opera takes newlines after BODY or HTML close tag and adds them to BODY contents AFAIK. This is probably where the extra CR LF comes from.

hallvors