Are there any rules regarding special characters/entities and innerHTML?

让人想犯罪 __ 提交于 2019-12-11 07:20:17

问题


When I use innerHTML from javascript, the browser (Safari and Firefox at least) seem to replace certain characters and numeric entities with their named entities.

The character \xa0 (non breaking space) gets replaced by  , < (lesser than) gets replaced by <. But for example the umlaut ü is not replaced with ü.

I have not found any documentation for this behaviour.

A simple demo:

<h2 id="withoutnbsp">This does not use en be es pe (uses the \xa0 character)</h2>
<script>alert(document.getElementById("withoutnbsp").innerHTML);</script>

A more elaborate demonstration can be found here:

http://gist.github.com/89434

You can use the "raw" link on the gist page, to view it in your browser.

I need to know exactly which characters innerHTML replaces. Any help is appreciated. Thanks.


回答1:


The HTML 5 spec has rules for serializing an HTML fragment when you call innerHTML on it, documented here: Serializing HTML fragments (note that innerHTML isn't in the HTML 4 spec, so the HTML 5 spec is the current reference).

TLDR version of the spec: Spaces, angle brackets, ampersands, equals signs and double quotes are the only chars that get escaped when innerHTML is called.




回答2:


It's probably replacing them with HTML character entities, as per the HTML spec.



来源:https://stackoverflow.com/questions/711720/are-there-any-rules-regarding-special-characters-entities-and-innerhtml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!