Timo Huovinen
Timo Huovinen

Reputation: 55653

Painlessly pass HTML to javascript

I need to pass html to javascript so that I can show the html on demand. I can do it using textareas by having a textarea tag with the html content on the page, like so: <textarea id="html">{whatever html I want except other textareas}</textarea> then using jquery I can present it on the page:

$("#target").html($("#html").val());

What I want to know is how to do it properly, without having to use textareas or having the html present in the <body> of the page at all?

Upvotes: 1

Views: 4990

Answers (4)

Timo Huovinen
Timo Huovinen

Reputation: 55653

Just like remy mentioned, you can use jQuery templates, and it's even cooler if you combine it with mustache! (which supports a lot of platforms)

Plus the mustache jQuery plugin is way more advanced than jQuery templates.

https://github.com/jonnyreeves/jquery-Mustache

Upvotes: 0

Remy
Remy

Reputation: 12713

You could use jquery templates. It's a bit more complex, but offers lots of other nice features.

https://github.com/codepb/jquery-template

Upvotes: 2

George Reith
George Reith

Reputation: 13476

As far as I know there is no painless way to do this due to the nature of html and javascript.

You can store your html as a string in a javascript variable such as:

var string = '<div class="someClass">your text here</div>';

However you should note that strings are enclosed within ether ' or " and if you use ether in your html you will prematurely end the string and cause errors with invalid javascript.

You can decide to only use one type of quote in your html say " and then ' to hold strings in javascript, but a more concrete way is to escape your quotes in html like so:

<div \"someClass\">your text here</div>

By putting \ before a special character you are telling it that it should ignore this character, however when you go to print it out the character will still print but the \ character won't, giving you functioning html.

Upvotes: 0

deceze
deceze

Reputation: 522500

Just save it in a variable:

<script type="text/javascript">
  var myHTML = '<div>Foo Bar</div>';
</script>

Upvotes: 1

Related Questions