0

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"

Jeromy French
  • 11,812
  • 19
  • 76
  • 129

1 Answers1

2

You can simply double-escape the \n to accomplish this:

var msg="Hi there\nGood to see you\nAlways a pleasure",
    returnElement=function(message) {
        document.getElementById("manipulate_me").innerHTML='<span onClick="alert(\''+message.split("\n").join("\\n")+'\')+'\');">click me and I throw a JavaScript error</span>';
    };

returnElement(msg);

Here's the updated jsfiddle: http://jsfiddle.net/HetQD/15/

Jeromy French
  • 11,812
  • 19
  • 76
  • 129
Robert Messerle
  • 3,022
  • 14
  • 18