Browsers disagree about the text of a body element

Posted by Charles Anderson on Stack Overflow See other posts from Stack Overflow or by Charles Anderson
Published on 2010-05-20T16:44:28Z Indexed on 2010/05/21 9:10 UTC
Read the original article Hit count: 273

Filed under:
|
|
|
|

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.

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about chrome