I'm maintaining a function that creates an element on the DOM with the onclick
event‡ set to a parameter passed to the function. It works very similarly to this:
var msg="Hi there\nGood to see you",
returnElement=function(message) {
document.getElementById("manipulate_me").innerHTML='<span onClick="alert(\''+message+'\');">click me and I throw a JavaScript error</span>';
};
On an HTML page including <div id="manipulate_me">Gets replaced</div>
, executing returnElement(msg);
results in this error (see for yourself on the jsfiddle at http://jsfiddle.net/jhfrench/HetQD/):
Uncaught SyntaxError: Unexpected token ILLEGAL
When I inspect the DOM, I see this (notice the new line within the alert()
):
<span onclick="alert('Hi there
Good to see you');">click me and I throw a JavaScript error</span>
How do I pass a string with one or more embedded new line codes?
Caveats:
- I'm working on a closed system that's recently upgraded to IE8.
- Because this template is used throughout the system, augmenting the code with jQuery is not possible
‡-I know, I know--"maintaining", not "writing"