Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to assign a block of html code to a javascript variable

what is the syntax to store a block of html code to a javascript variable?

<div class='saved' > <div >test.test</div> <div class='remove'>[Remove]</div></div> 

I want to assign the above code to a variable 'test'

var test = "<div class='saved' > <div >test.test</div> <div class='remove'>[Remove]</div></div>"; 

but it does not work, which are the correct syntax for assigning the code?

TIA

like image 988
jamex Avatar asked Aug 04 '10 22:08

jamex


People also ask

How do you assign something to a variable in JavaScript?

The simple assignment operator ( = ) is used to assign a value to a variable. The assignment operation evaluates to the assigned value. Chaining the assignment operator is possible in order to assign a single value to multiple variables.

How do you assign a value to a variable in HTML?

Use the <var> tag in HTML to add a variable. The HTML <var> tag is used to format text in a document. It can include a variable in a mathematical expression.


2 Answers

Greetings! I know this is an older post, but I found it through Google when searching for "javascript add large block of html as variable". I thought I'd post an alternate solution.

First, I'd recommend using single-quotes around the variable itself ... makes it easier to preserve double-quotes in the actual HTML code.

You can use a backslash to separate lines if you want to maintain a sense of formatting to the code:

var code = '<div class="my-class"> \         <h1>The Header</h1> \         <p>The paragraph of text</p> \         <div class="my-quote"> \             <p>The quote I\'d like to put in a div</p> \         </div> \     </div>'; 

Note: You'll obviously need to escape any single-quotes inside the code (e.g. inside the last 'p' tag)

Anyway, I hope that helps someone else that may be looking for the same answer I was ... Cheers!

like image 180
Brian Ayers Avatar answered Sep 21 '22 22:09

Brian Ayers


 var test = "<div class='saved' >"+  "<div >test.test</div> <div class='remove'>[Remove]</div></div>"; 

You can add "\n" if you require line-break.

like image 43
draganHR Avatar answered Sep 23 '22 22:09

draganHR