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
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.
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.
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!
var test = "<div class='saved' >"+ "<div >test.test</div> <div class='remove'>[Remove]</div></div>";
You can add "\n" if you require line-break.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With