PDA

View Full Version : element.innerText difference in Browsers


hotwheelharry
05-13-2010, 04:00 AM
My question is how or what property do I use to get the text inside of elements (nested or unnested) with all the new line characters?
I dont want to have to write a function that takes apart all the elements and does this manually.
So far, only Chrome seems to support this property correctly.

I have some code...

<!--Head-->
<body>


<div id="root">
<br/>
<div>this is <span style="color:red">red </span>text</div>
<p>this is another line</p>
</div>

<textarea id="txt" style="width:300px; height:300px;"></textarea>

</body>

<script type="text/javascript">
var txt = document.getElementById("txt");
var root = document.getElementById("root");

txt.value = root.innerText;

var c = 0;
var r = 0;
for(var i = 0; i < txt.value.length; i++)
{
if(txt.value[i] == "\n")
{
c++;
}
if(txt.value[i] == "\r")
{
r++;
}
}

alert(c + "\n" +r); // output the line character counts
</script>

</html>


Here are the results displayed in the textarea in the following browsers...

Chrome:
all text with \n character separating new lines

FF:
undefined

IE:
all text but NO new line characters

My question is how or what property do I use to get the text inside of elements (nested or unnested) with all the new line characters?
I dont want to have to write a function that takes apart all the elements and does this manually.
So far, only Chrome seems to support this property correctly.

abduraooft
05-13-2010, 08:42 AM
You'd need to use .textContent for FF, see http://www.quirksmode.org/dom/w3c_html.html

Kor
05-13-2010, 09:21 AM
Simply use innerHTML instead of innerText. You might need probably to bring everything on lowercase for IE (which in innerHTML has the horrible habit to return tags name and attributes in uppercase), but it would not be a major problem, I guess.

hotwheelharry
05-17-2010, 08:20 PM
Thank you abduraooft. Nice link btw

This does work in FF. Is there a way I can get the new line information too. Like if the following ends up in a content editable div...


This is some<br/>code on a<br/>new line


textContent spits out...

This is somecode on anew line


but I would expect...

This is some\ncode on a\nnew line


At least, that's how chrome does it (the 2nd way, that is). It adds the new line characters where there is a br.
Do you know how to get FF to do this

rnd me
05-17-2010, 09:38 PM
At least, that's how chrome does it (the 2nd way, that is). It adds the new line characters where there is a br.
Do you know how to get FF to do this

just insert a text node with "\n" before each <br /> tag:

var r = document.getElementsByTagName("br");
for(var i=0, mx=r.length;i<mx;i++){
var nd=document.createTextNode("\n");
r[i].parentNode.insertBefore(nd, r[i]);
}

hotwheelharry
05-18-2010, 04:54 PM
alright, I'll just do that.

I just wanted to make sure there was not a fast "native code" way already there.

thanks