How to adding special html chars without using innerHTML

Go To StackoverFlow.com

2

So I'm working on a micro lib, html.js, and basically it creates text nodes with document.createTextNode but when I want to create a text node with a b I get a b so I'm wondering how to escape the & char, without using innerHTML ideally..

2012-04-05 18:18
by erikvold
Shouldn't that be & - James Montagne 2012-04-05 18:19
& = & in HTM - XXX 2012-04-05 18:20
possible duplicate of Is it possible to get the the createTextNode method to render html tags?James Montagne 2012-04-05 18:22
@James, that question is about html tags, and I'm talking about special chars, also suggested solution there was using innerHTML which I cannot use (too many reasons) - erikvold 2012-04-05 18:29
Actually innerHTML can't be used, since it would destroy nodes already added to a parentNode - erikvold 2012-04-05 18:31
Another reason I want to avoid using innerHTML is to prevent users from mangling an html string together and using that - erikvold 2012-04-05 20:18


4

Javascript supports the \uXXXX notation, so in the case of a non-breaking space, that would be \u00A0.

document.createTextNode('a\u00A0b');

That's as far as you can get. It's a text node, consisting only of text, and there's no difference between texts created from entity references or from normal characters.

If that's not what you want, you should take a second look at innerHtml. Can't you read it, modify it and put it back?

2012-04-05 18:47
by Mr Lister
Beat me to it. Here's an example: http://jsfiddle.net/AXdpJ - James Montagne 2012-04-05 18:48
html.js adds listeners to html elements via addEventListener, and returns a reference to the HTMLElement so I can't have the node overwritten or wiped out using innerHTML - erikvold 2012-04-05 20:14
This looks like a good way for users to avoid having to use html entities, but I'd like to have a solution for them if they do use it - erikvold 2012-04-05 20:21
Nice, do have any good references for those kinds of notations - Nick Rolando 2012-04-05 20:56
Here's a nice one: http://mathiasbynens.be/notes/javascript-escape - Mr Lister 2012-04-05 21:11
maybe it's possible to do a character mapping - erikvold 2012-04-05 22:34
You can do things like replace(' ', ' ') manually, but there is no built in routine that does all of them. You'll need an exteral library for that - Mr Lister 2012-04-06 06:04


0

There's not much functionality in js to encode/decode html entities. Seems like there some libraries out there, though, that can help you achieve this. Here is one I found on goodle.. haven't tried it, but you can check it out, or look for others.

http://www.strictly-software.com/htmlencode

2012-04-05 18:28
by Nick Rolando
I hope you can find a better answer than using a library for this. I would be interested ; - Nick Rolando 2012-04-05 18:41
Ads