简体   繁体   中英

no need to escape innerHTML characters in javascript?

Should I not escape the double quotes in "markup4" and such? To my surprize this plain works. If I replace them by the &quot thing it doesn't.

<script type="text/javascript">

    function test3(){
    document.getElementById('div21').innerHTML += '<div class = "markup4"><br>blablablabla1.<br><br></div><div class = "markup3"><br>blablabla2.<br><br></div>';
    }

</script>

These work without escape:

innerHTML = "<div class = 'markup4'>";
innerHTML = '<div class = "markup4">';

Note: When the " used outside, the ' works properly inside. (and the opposite)

These need the escape:

innerHTML = '<div class = \'markup4\'>';
innerHTML = "<div class = \"markup4\">";

Note: When you use the double quote outside and inside, the inside's " needs to be escaped by \\ . (same for single quotes)

These will break:

innerHTML = "<div class = "markup4">";
innerHTML = '<div class = 'markup4'>';

First the string is parsed to an internal javascript string representation, so you first need to escape for javascript string literals. The result of this would be the same as what you already have - so no modification is needed.

Now you have

<div class = "markup4"><br>blablablabla1.<br><br></div><div class = "markup3"><br>blablabla2.<br><br></div>

Internally in javascript memory.

After this, it's just like you would write that as normal HTML, so of course, if you use &quot; it will not work.

It can get pretty complicated to store strings that go through 2 different interpretations, which is why you shouldn't do this but use templating engines with the templates stored in other files or custom script elements on the page, which would allow you to focus only on the html interpretation.

escape should be used when you want to include quotes within the data,

ex: He said, "Please use this!" should get escaped like:

He said, \\" Please use this !\\".

Otherwise they work without any troubles.

Hope I've clarified.

Don't forget browsers render their own innerHtml based on what you give them which can cause problems if nesting innerHtml code.

I found the &apos; and &quot; codes useful here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM