Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does the HTML symbol for ▶ not work in document.title

Tags:

javascript

I tried using ► while setting document.title but it did not render the play symbol, just showed those same characters.

I'm able to paste ▶ directly into the code, which works. I'm just curious why the first way wouldn't work.

Thanks!

like image 474
d-_-b Avatar asked Jun 05 '13 03:06

d-_-b


Video Answer


2 Answers

&#9658; is an HTML entity reference, but document.title does not contain HTML; it contains plain text. For example, if I set document.title to <strong>Hello</strong> <em>world</em>, it would display that literally, rather than showing Hello world. The same goes for any other piece of HTML, including entity references.

To be clear, you can include entity references in a title tag. They will be interpreted when the page is parsed. However, document.title accesses the text after it has been parsed and all entities substituted. document.title will access the text of the title tag, not the HTML inside of it that was originally used to create it. Similarly, setting document.title does not make any HTML inside of it be automatically interpreted.

Including the character literally can cause issues if the browser for some reason interprets your page in a different character encoding than it's actually in. HTML entities protect against this in HTML, but there's also a way to escape them in JavaScript. In particular, you can include ► in JavaScript with the string escape \u25ba. (965810 converted to base 16 is 26BA16)

like image 77
icktoofay Avatar answered Sep 28 '22 14:09

icktoofay


The other answer is correct in that a HTML document's title is plain text and cannot contain markup.

However, to be clear, you can use &#9658; in the HTML source (ie, <title>&#9658;</title>). The parser will convert the entity in to the proper character in the string that gets stored in the DOM.

You're running in to an issue when you set document.title. The HTML parser does not apply to JavaScript, even if the script is inline in a HTML document. Your script simply sets the document's plain text title to the literal ampersand-pound-9658-semicolon because that sequence of characters has no special meaning in script.

If you want to escape a character in script source, use a JavaScript escape sequence. Unicode escape sequences in JavaScript require the hex representation of the Unicode code point, and your entity is using the decimal representation (9568). Convert to hex and we get 25BA:

document.title = '\u25ba Playing';
like image 37
josh3736 Avatar answered Sep 28 '22 15:09

josh3736