最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Output using innerHTML - Stack Overflow

programmeradmin0浏览0评论

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?

Share Improve this question edited Sep 28, 2020 at 17:21 Alex 1,5801 gold badge15 silver badges27 bronze badges asked Apr 17, 2009 at 17:24 IrisIris 1,3414 gold badges17 silver badges19 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 4
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>';
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>";
发布评论

评论列表(0)

  1. 暂无评论