no need to escape innerHTML characters in javascript?
Asked Answered
F

4

8

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>
Favianus answered 19/1, 2013 at 11:33 Comment(4)
It works. As well as innerHTML = "<div class = 'markup4'>".Margalit
yeah, you shouldn't escape the quote for that. Actually &quot is use for html. for example &quotyes&quot will return "yes"Riebling
you don't need to escape it as your main string quotation starts with ' and until it encounters another ' the string is valid. and " != 'Mitzvah
mavili, very clear explanation, thank youFavianus
F
16

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'>';
F answered 19/1, 2013 at 11:39 Comment(0)
C
1

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.

Cranny answered 19/1, 2013 at 11:37 Comment(0)
L
1

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.

Luncheon answered 19/1, 2013 at 11:42 Comment(0)
A
0

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.

Annabelle answered 22/8, 2018 at 14:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.