8

I have a javascript variable I need to create like this:

var HTMLContent = '<div class="className">HTML Content</div>';

How can I format it in an easier to read format because I'm going to want to create multiple lines of HTML.

e.g.

var HTMLContent = '
<div class="className">
  HTML Content
</div>
';

Is something like that possible?

It would also be good if I could import via URL e.g. var HTMLContent = 'http://domain.com/page.html';

7 Answers 7

10
 var longStr = "You can split\
 the string onto multiple lines\
 like so";

An example using your HTML would be:

var longStr = 
    '<div class="className">\
        HTML Content\
    </div>';

To load external HTML, check out jQuery's load method:

$('#result').load('ajax/test.html');
Sign up to request clarification or add additional context in comments.

2 Comments

That's the best way so far, wonder if there is a better way at all.
This is still not very maintainable over time. A better approach is to store your template markup as part of your HTML code instead of injecting it in your javascript.
5

In your page markup, add a hidden template div, like:

<div id="contentTemplate" style="display: none;">
    <div class="className">
        HTML_CONTENT
    </div>
</div>

...then in your JavaScript, you can do something like:

var newContent = 'The content for the new element';
var templateContent = document.getElementById("contentTemplate").innerHTML;
var htmlContent = templateContent.replace("HTML_CONTENT", newContent);

You could also use an AJAX request to pull the value of newContent from a URL to get your dynamic content loading working. If you plan on doing this, however, then I suggest you investigate using a framework like jQuery, which can greatly simplify this process.

Comments

5

You can also use backticks

function myFunc() {
var HTMLContent =`
<div class="className">
    <div>HTML Content</div>
</div>
`;

document.getElementById('demo').innerHTML = (HTMLContent);

}
myFunc()
<div id="demo"></div>

Comments

0
var HTMLContent = 
    '<div class="className">' +
    'HTML Content' +
    '</div>';

Comments

0

You can do something like:

 var HTMLContent = '<div class="ClassName">' + 
   'HTML Content' +
    '</div>';

Comments

0

You can use escape characters:

var HTMLContent = '<div class="className">\n\tHTML Content\n</div>';

I may have misinterpretted the question, you want the javascript to be more readable, not the html stored in the variable?

1 Comment

Yes, you're right. He's asking for some way to store easy readable HTML into a javascript variable.
0
var HTMLContent = "" +
"<div class=\"className\">\n" +
"    HTML Content\n" +
"</div>\n" +
"";

This way, the script that writes it it pretty and the code it writes will be pretty too if someone were to view-source.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.