title: Encode HTML attributes when inserting HTML in the DOM
body: <p>I have questions on preventing XSS attacks.</p>
  
  <p>1) Question:</p>
  
  <p>I have an HTML template as Javascript string (trusted) and insert content coming from a server request (untrusted). I replace placeholders within that HTML template strings with that untrusted content and output it to the DOM using innerHTML/Text.</p>
  
  <p>In particular I insert texts that I output in <code>&lt;div&gt;</code> and <code>&lt;p&gt;</code> tags that are already present in the template HTML string and form element values, i.e. texts in input tag's value attribute, select option and textarea tags.</p>
  
  <p>Do I understand correctly that I can treat every inserted text mentioned above as HTML subcontext thus I only encode like so: encodeForJavascript( encodeForHTML( inserted_text ) ). Or do I have to encode the texts that I insert into value attributes of the input fields for the HTML Attribute subcontext?</p>
  
  <p>After reading up on this issue on OWASP I am inclined to think that latter is only necessary in case I set the attribute with unstrusted content via Javascript like so: <code>document.forms[ 0 ].elements[ 0 ].value = encodeForHTMLAttribute</code>, is that correct?</p>
  
  <p>2) Question:</p>
  
  <p>What is the added value of server side encoding server responses that enter the client side via Ajax and get handled anyway (like in question 1). In addition, don't we risk problems when double encoding the content?</p>
  
  <p>Thanks</p>