Iris
Iris

Reputation: 1341

Output using innerHTML

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?

Upvotes: 0

Views: 8134

Answers (5)

David
David

Reputation: 1927

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>";

Upvotes: 0

Dan Lew
Dan Lew

Reputation: 87440

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>';

Upvotes: 4

moff
moff

Reputation: 6503

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.

Upvotes: 0

George
George

Reputation: 7944

document.getElementById('id').innerHTML = jsVar;

Upvotes: 2

David
David

Reputation: 1927

var element= document.getElementById("elementID");
element.innerHTML = someHTMLstring;

Upvotes: 2

Related Questions