Dave
Dave

Reputation: 320

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>

becomes:

<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:

<option>&lt;&sol;option&gt;</option>

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?

Thanks.

Upvotes: 7

Views: 4838

Answers (1)

Luka Kerr
Luka Kerr

Reputation: 4239

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:

<option></option></option>

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";
}
<select>
  <option>&lt;/option&gt;</option>
  <option>&#60;/option&#62;</option>
  <option>&lt;&sol;option&gt;</option>
  <option id="css-option"></option>
</select>

Upvotes: 1

Related Questions