PDA

View Full Version : createTextNode()



Trinithis
06-24-2007, 04:31 PM
How can you use document.createTextNode() and have it retain blank spaces (" ")? My FF1 will chop the extra whitespace, while IE6 won't. Replacing the spaces with " " doesn't work either. I don't want to use "pre" or "innerHTML". Any ideas?

jscheuer1
06-24-2007, 04:57 PM
Use the javascript hex entity for a non-breaking space:


var test=document.createTextNode('\xa0test');

That is the only way I know of to do exactly what you propose. There are other avenues to get the effect desired, depending upon just what that is, like appending a span with padding which itself has had the text node appended to it.

Notes: FF is just formating the text in the same manner as it would if the element and text were hard coded. Like if you had:


<script type="text/javascript">
onload=function(){
var test=document.createTextNode(' test');
document.body.appendChild(test);
}
</script>
</head>
<body>
test
</body>

The output would be:

test test

- the space would be preserved, but with:


<script type="text/javascript">
onload=function(){
var test=document.createTextNode(' test');
document.body.appendChild(test);
}
</script>
</head>
<body>
<div>test</div>
</body>

the output is:

test
test

Since the space in the text node is now leading in its parent, it is ignored, just as it would be if you had:


<body>
<div>test</div>
test
</body>

with no script at all.

Twey
06-24-2007, 05:31 PM
Try .style.whiteSpace = "pre";

Trinithis
06-24-2007, 05:40 PM
Thanks for the help. The \xa0 worked exactly how I wanted.