Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 491
wubbewubbewubbe Avatar asked Jan 19 '13 11:01

wubbewubbewubbe


2 Answers

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'>';
like image 63
wildhaber Avatar answered Sep 23 '22 02:09

wildhaber


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.

like image 40
SHANK Avatar answered Sep 21 '22 02:09

SHANK