Norbert Hartl
Norbert Hartl

Reputation: 10851

Do I need to do string sanitation before adding to DOM?

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.

Upvotes: 0

Views: 680

Answers (1)

Quentin
Quentin

Reputation: 944559

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.

Upvotes: 2

Related Questions