Tutorial :jQuery('body').text() gives different answers in different browsers



Question:

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.


Solution:1

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.


Solution:2

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.


Solution:3

As different browsers behave in different ways, I suggest:

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

This should produce consistent results.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »