views:

56

answers:

1

In our team we came up with the idea that we have to do sanitizing of strings before added to the DOM. We expected at least that double quotes would be troublesome if used in setAttribute and < and > if added to the node content.

The first tests showed something different. We are using innerHTML to set a nodes content. This escapes all unsafe characters by its own. But even setAttribute does escape < and >

So is this always the case because I couldn't find anything on google? I don't know if there are browsers out there that would fail.

+2  A: 

innerHTML is editing the HTML inside an element and generating DOM nodes from it - you need write HTML according to the normal rules (e.g. you can't use a < character unless it is followed by a non-name character). Browsers will perform their usual error recovery though.

I don't understand why your experience of innerHTML differs from that.

createTextNode, setAttribute, etc edit the DOM directly. HTML is not involved, so you don't have to deal with characters that have special meaning in HTML.

David Dorward
I took a second look and we aren't using innerHTML. As we have single nodes where we can set the nodeValue. And then I think your answer icludes this that every DOM method works in away that < and > are handled just right.
Norbert Hartl