Browsers disagree about the text of a body element
- by Charles Anderson
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.