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?
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?
5 Answers
Reset to default 4var 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>';
var element= document.getElementById("elementID");
element.innerHTML = someHTMLstring;
document.getElementById('id').innerHTML = jsVar;
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.
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>";