Reputation: 1744
If you create an HTML element with JS using a string like the following, how can you add the extra quotes required within an onclick event? Since I have already exhausted double and single quotes, is there an elegant way of making this work?
var foo_td="<td onclick='window.open('newpage.html', '_blank')'>Open Page</td>";
Upvotes: 0
Views: 220
Reputation: 68433
You need to replace innermost single quotes '
with double quotes "
and escape them with single backslash \
, like this:
var foo_td="<td onclick='window.open(\"newpage.html\", \"_blank\")'>Open Page</td>";
Why escape quotes at first place
This is because when the onclick
event will be fired on this td
and if there are no quotes (if quotes not escaped), then it will look for a variable named newpage.html
and _blank
and give an error because these variables (most likely) won't exist.
Why not only single backslash with single quote
Single-backslash will only escape the string for the evaluation of this string expresion, and by the time this value is stored in a string it will ignore this backslash.
Why not double backslash with single quote
By the time nodes are rendered on DOM (can check this on Developer Tools of your browser), its attribute values are enclosed inside a double quote rather than a single quote. So, it will be rendered as this and hence give an error.
<div onclick="window.open(\" newpage.html\',="" \'_blank\')'="">Open Page</div>
So, based on three reasons given above you should always escape double quote if you want to pass a string parameter to a function call from an attribute.
Upvotes: 4