Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 "<&sol;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.

like image 730
Dave Avatar asked Oct 31 '16 00:10

Dave


People also ask

What does escaping characters mean in HTML?

Escaping in HTML means, that you are replacing some special characters with others. In HTML it means usally, you replace e. e.g < or > or " or & . These characters have special meanings in HTML. Imagine, you write <b>hello, world</b> And the text will appear as hello, world.


1 Answers

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>
like image 54
Luka Kerr Avatar answered Oct 12 '22 09:10

Luka Kerr