tags:

views:

421

answers:

5

I need to output the contents of a Javascript variable which has html code in it:

var jsVar = '<div>
<p> Sample text </p>
<img src="some image.jpg"  alt="" />
<div>';

I want to add it to an object on the page using innerHTML. How do I do it ?

+2  A: 
var element= document.getElementById("elementID");
element.innerHTML = someHTMLstring;
David
+2  A: 
document.getElementById('id').innerHTML = jsVar;
George
+4  A: 
var element = document.getElementById("myElementId");
element.innerHTML = jsVar;

This is assuming you get your element via getElementById(); there are many ways to get elements in JavaScript besides that, like getElementsByTagName() (which returns an array of elements) or by listening to events on elements that pass themselves in as an argument.

Also, the way you're loading the string into jsVar won't work currently. You either need to put it all on one line, or concatenate multiple strings, like below:

// Method 1
var jsVar = '<div><p> Sample text </p><img src="some image.jpg"  alt="" /><div>';

// Method 2
var jsVar = '<div>' +
    '<p> Sample text </p>' +
    '<img src="some image.jpg"  alt="" />' +
    '<div>';
Daniel Lew
I am getting a unterminated string exception. How do I remove the line feeds,spaces etc ?
Iris
If you're loading jsVar the way you wrote above, then the error you're getting is because the string is being defined over multiple lines. You need to either have that whole string defined on one line, or concatenate multiple strings on each line. I'll edit my answer to show you how.
Daniel Lew
A: 

Also note that you'll have to use \n instead of linebreaks in JavaScript:

var jsVar = '<div>\n<p> Sample text </p>\n<img src="some image.jpg"  alt="" />\n<div>';

If you don't do this, you'll get a "unterminated string literal" error.

moff
yes ..I am having issues doing that ..replacing all the line feeds with \n
Iris
If you're doing innerHTML, you don't have to have the '\n's, because they're superfluous then.
Daniel Lew
You're right, but it's still a good practice, IMHO.
moff
A: 

The string you're assigning, can't span multiple lines:

this doesn't work

ttt = "ab
c";

this does

ttt = "ab" +
      "c";

best would be escaping all the special characters, and getting rid of line feeds in your string (I don't like strings done with ', although it's a personal thing :).

var jsVar = "<div><p> Sample text </p> <img src=\"some image.jpg\"  alt=\"\" /><div>";
David
Just a head's up, you can edit your own posts to extend your answer. (I did so just to cover this situation, in fact.)
Daniel Lew
could u elaborate on how I could escaping all the special characters, and getting rid of line feeds. Thanks
Iris