开发者

problem with IE which removes new lines from $("#content").text()

开发者 https://www.devze.com 2023-01-13 20:35 出处:网络
problem with IE which removes new lines from $(\"#content\").text() HTML Code <div id=\"content\">

problem with IE which removes new lines from $("#content").text()

HTML Code

<div id="content">
<p>hello world</p>
<p>this is a paragraph</p>
</div>

jQu开发者_运维知识库ery Code

alert($("#content").text()); 

result (IE) IE removes new line (\n) how can i fix this problem ?

hello worldthis is a paragraph

result (FF)

hello world
this is a paragraph

take a look : http://jsfiddle.net/vB3bx/


It works fine if you use the div's innerText property. Try replacing

alert($("#content").text());

with

alert( document.getElementById( "content" ).innerText );


Internet Explorer normalizes all white-space and new-line characters into the SPACE character. As far as I know, there is nothing you can do about it.

btw, it seems that IE9 beta changed this behavior. I get new-lines in it.


I'm pretty sure Sime Vidas is correct. I've tried just about everything and whatever I try (innerText, innerHTML, jQuery methods, TextRange, cloning element and putting it inside a pre element etc etc) white space is removed. I'm guessing IE will just remove it on any type of call. It clearly is there during rendering since a white-space:pre will show it, but retrieving it through javascript will always remove the white space except for pre and textarea content.

This behavior has changed in IE9. The only solution in older versions would be to replace new line characters with
tags (or anything really, semicolon etc) on the server if possible and then replace them back into \n in javascript after retrieving the text content.


Not sure you're going to find a solution using text() if you consider the following:

Due to variations in the HTML parsers in different browsers, the text returned may vary in newlines and other white space.

at http://api.jquery.com/text/

0

精彩评论

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