Dave Dave - 3 months ago 17
HTML Question

How to properly escape text inside <option> tag?

When inserting untrusted text into an HTML document, there are certain special characters you must escape (e.g. <, &, ", etc.). (" for quoted attributes). For example:

<div>Some tags are <b> and <div></div>


<div>Some tags are &lt;b&gt; and &lt;div&gt;</div>

(One can debate the need for &gt; but that's not relevant here.)

That's great but what about inside an option tag? If I want the text to be "</option>", how do I do it?

This does not work:


What I find is that the HTML character entities, (&lt;,&gt;, etc.) are dropped. I've tried both Chrome and Firefox. I assume this is related to the fact that the option tag cannot contain nested tags. Google has failed me on this one. :(

And a related question: Since <option> has special escaping behavior as shown above, and we know <script> has its own behavior. Is there a complete list somewhere of all the HTML tags that have special escaping behavior and what there rules are?



If I understand your question properly, as demonstrated in the below snippet, you can escape HTML entities inside the <option> tag perfectly fine (tested on Firefox, Chrome & Safari).

So you are able to have the text </option> inside an option tag. This is done using the HTML entities that represent the < and > characters

Essentially it is the same as having:


Although the middle </option> is not treated as a closing tag, but rather it is shown that way in the browser

As a side note, the only limitation using <option> tags when escaping characters lays in the :before and :after CSS pseudo elements. W3 suggests that you cannot prepend/append content to the <option> tag using these pseudo elements. Although for some reason, in Firefox 48 this does infact work

#css-option:before {
  content: "any text";
  <option id="css-option"></option>