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

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

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.

we can use backticks (``) without any error.. eg: <div>"test"<div>
we can store large template(HTML) inside the backticks which was introduced in ES6 javascript standard
No need to escape any special characters
if no backticks.. we need to escape characters by appending backslash()
eg:" \"test\""

I recommend to use mustache templating frame work. https://github.com/janl/mustache.js/.
<body>
....................
<!--Put your html variable in a script and set the type to "x-tmpl-mustache"-->
<script id="template" type="x-tmpl-mustache">
<div class='saved' >
<div >test.test</div> <div class='remove'>[Remove]</div></div>
</script>
</body>
//You can use it without jquery.
var template = $('#template').html();
var rendered = Mustache.render(template);
$('#target').html(rendered);
Why I recommend this?
Soon or latter you will try to replace some part of the HTML variable and make it dynamic. Dealing with this as an HTML String will be a headache. Here is where Mustache magic can help you.
<script id="template" type="x-tmpl-mustache">
<div class='remove'> {{ name }}! </div> ....
</script>
and
var template = $('#template').html();
// You can pass dynamic template values
var rendered = Mustache.render(template, {name: "Luke"});
$('#target').html(rendered);
There are lot more features.

Just for reference, here is a benchmark of different technique rendering performances,
http://jsperf.com/zp-string-concatenation/6
m,

Modern Javascript implementations with the template syntax using backticks are also an easy way to assign an HTML block of code to a variable:
const firstName = 'Sam';
const fullName = 'Sam Smith';
const htmlString = `<h1>Hello ${fullName}!</h1><p>This is some content \
that will display. You can even inject your first name, ${firstName}, \
in the code.</p><p>Search for \
stuff on the Google website.</p>`;

you can make a javascript object with key being name of the html snippet, and value being an array of html strings, that are joined together.
var html = {
top_crimes_template:
[
'<div class="top_crimes"><h3>Top Crimes</h3></div>',
'<table class="crimes-table table table-responsive table-bordered">',
'<tr>',
'<th>',
'<span class="list-heading">Crime:</span>',
'</th>',
'<th>',
'<span id="last_crime_span"># Arrests</span>',
'</th>',
'</tr>',
'</table>'
].join(""),
top_teams_template:
[
'<div class="top_teams"><h3>Top Teams</h3></div>',
'<table class="teams-table table table-responsive table-bordered">',
'<tr>',
'<th>',
'<span class="list-heading">Team:</span>',
'</th>',
'<th>',
'<span id="last_team_span"># Arrests</span>',
'</th>',
'</tr>',
'</table>'
].join(""),
top_players_template:
[
'<div class="top_players"><h3>Top Players</h3></div>',
'<table class="players-table table table-responsive table-bordered">',
'<tr>',
'<th>',
'<span class="list-heading">Players:</span>',
'</th>',
'<th>',
'<span id="last_player_span"># Arrests</span>',
'</th>',
'</tr>',
'</table>'
].join("")
};

Please use symbol backtick '`' in your front and end of html string, this is so called template literals, now you able to write pure html in multiple lines and assign to variable.
Example >>
var htmlString =
`
<span>Your</span>
<p>HTML</p>
`

Related

Storing HTML in a JS variable but preserving the HTML variables

Im trying to save some HTML in a JS variable by using the backtick formatting however is it possible to preserve the HTML variable according to the following example
var msg = "This is a test" + "\n" + "Test"
Im attempting to store this variable as a HTML paragraph while keeping the linebreaks
var emsg = '<p style="white-space: pre-wrap;"><\"{msg}"\</p>'
But when sending that content in an email to myself (Using Emailjs) I get the following
<"{msg}"
Any clue what I'm doing wrong? Thanks!
You are using single quotes ('), not backticks (`)
Placeholders in template literals are indicated by a dollar sign ($), which you are missing.
var msg = "This is a test" + "\n" + "Test"
var emsg = `<p style="white-space: pre-wrap;"><\"${msg}"\</p>`
console.log(emsg)
You could go with template literals like #spectric showed.
or you can go with simple quote using + to seperate it with msg variable
var msg = "This is a test" + "\n" + "Test";// V V
var emsg = '<p style="white-space: pre-wrap;"><\"'+msg+'"\</p>';
console.log(emsg);
as described + removing the extra <\" and "\ probably
var emsg = <p style="white-space: pre-wrap;">${msg}</p>

How to echo data-ac-chart="'bar'" in jQuery?

I can't 'echo' the ' ' closers in jQuery.
I tried this method:
$('#run').append("<pre><code class='prettyprint'>"+data+"</code></pre> <div data-ac-chart="+"'"+"bar"+"'"+" data-ac-data='data' data-ac-config='config' class='chart'></div>");
But this will show:
<div data-ac-chart="bar" data-ac-data="data" data-ac-config="config" class="chart"></div>
How to edit the jQUery code to the result will be this:
<div data-ac-chart="'bar'" data-ac-data="data" data-ac-config="config" class="chart"></div>
Not the neatest solution, but you could escape the double quotes.
<div data-ac-chart=\"'" + data + "'\"></div>
Example Here
$('#run').append("<pre><code class='prettyprint'>"+data+"</code></pre> <div data-ac-chart=\"'" + data + "'\" data-ac-data='data' data-ac-config='config' class='chart'></div>");
For a neater solution, I'd suggest checking out a JS templating engine.
Alternatively, you could also just change/add the value after you have appended the element:
Example Here
$('#run [data-ac-chart]').attr('data-ac-chart', "'" + data + "'");
Try this to add \ before the apostrophe, like this:
data-ac-chart="+"\'"+"bar"+"\'"
Josh was right with :
data-ac-chart="+\"'"+"bar"+"'\"
You can escape such characters using a backslash.
A) With single quotes around HTML attributes: (not recommended, here you have to escape the created attribute value)
var output = "<div data-ac-chart='\\\'bar\\\'' data-ac-data='data' data-ac-config='config' class='chart'></div>";
The multitude of backslashes is required here to mask the backslash and single quote inside the attribute from JavaScript. JS then outputs HTML with escaped attribute values:
"<div data-ac-chart='\'bar\'' data-ac-data='data' data-ac-config='config' class='chart'></div>"
B) With double quotes around HTML attributes: (recommended, write beautiful markup and everything will work out :-)
var output = '<div data-ac-chart="\'bar\'" data-ac-data="data" data-ac-config="config" class="chart"></div>';
C) A more readable approach using placeholders and string replacement:
var output = '<div data-ac-chart="{chart}" data-ac-data="{data}" data-ac-config="{config}" class="chart"></div>'
.replace( '{chart}', '\'bar\'' )
.replace( '{data}', 'data' )
.replace( '{config}', 'config' );
Concatenating strings is cumbersome and as you experience quite difficult to debug. That's why I recommend using a template approach as supported by underscorejs:
<!-- in your HTML -->
<script type="text/template" id="template">
<div>
<pre>
<code class='prettyprint'>
<%=data%>
</code>
</pre>
<div data-ac-chart='bar' data-ac-data='data' data-ac-config='config' class='chart'>
</div>
</div>
</script>
/* in your javascript */
$('#run').append(_.template($("#template").html())({
data : "var function(x) = { some code };"
}));
Make sure to load the underscorejs library. A working example is available in this jsfiddle

HTML in JavaScript function basics

Ok, I'm having a huge problem, and I've been looking for days about how to do this. Either I can't read well enough to understand it, or I'm stupid. I'm not sure what it is yet. I'll be honest and say that this is homework, but I've been struggling with this for 3 days now, and as its an online class, I can't go see my instructor and ask him what I'm doing wrong. I have emailed him, but his help is limited and vague, and I cannot figure this out. Anyway, to the point. I want to add HTML to the text that's going to be displayed in a new window using a JavaScript function. Here's the basics of what I have.
function myWindow(){
var pageContent, pageTitle;
pageTitle = document.write("Selected Image Preview");
document.write.style.textAlign="center";
pageContent = "<html><head><title>";
pageContent += pageTitle + "</title>";
pageContent += "<script>alert('The page ' + document.title + ' was created: ' + document.lastModified)</script>";
pageContent += "<h3>"Name of Image"</h3>";
pageContent += "</head><body align="center"><strong>" + "<font color= " violet ">"Here is the image you selected. "</font>";
pageContent += "</strong></body></html>";
}
Now, I have no idea what I'm doing wrong, considering I've read almost everything that I could find, searched all over this site, as well as dozens of others. I've tried the W3 schools, and some site that looked like it was last updated in 2001, and my book has absolutely NO examples of HTML being used inside the function (it's a javascript book, so the HTML help is very limited). Starting at the top, it tells me that "Uncaught SyntaxError: Unexpected token ILLEGAL junk.html:16" on the script line. Then it won't load the rest of the page. If I comment that out, it tells me that '<h3>' is an unexpected identifier, and it just keeps going. There's always something wrong and if I comment out the lines that give errors, then there's nothing left. Please help me figure out what I'm doing wrong. And if it's necessary, I am calling the function onload with the <body onload="myWindow();"> tag.
P.S. Please don't kill me if I've formatted this incorrectly. I did read the directions, and tried to format this as neatly as possible.
The biggest problem was that the closing </script> tag in the line with the call to alert() terminated the script, even though it was within a string literal. See the link in my comment to your original post. There were some other problems with quotes, and if a teacher is really teaching the <font> tag in 2014, I think I should track him down and throw up in his lap.
Note that the slash in </script> and the embedded double-quotes are now escaped with backslashes. That's the biggest change. Also, the function now returns the computed value so it can be used.
This code goes through a JavaScript console clean. It doesn't open any new windows, and it doesn't deal with the "style" line, which I couldn't figure out.
function myWindow(){
var pageContent, pageTitle;
pageTitle = "Selected Image Preview";
// document.write.style.textAlign="center"; // WTF?
pageContent = "<html><head><title>";
pageContent += pageTitle + "</title>";
pageContent += "<script>alert('The page ' + document.title + ' was created: ' + document.lastModified)<\/script>";
pageContent += "</head>";
pageContent += "<body style=\"text-align: center;\">";
pageContent += "<h3>Name of Image</h3>";
pageContent += "<strong>" + "<font color= \" violet \">\"Here is the image you selected. \"</font>";
pageContent += "</strong></body></html>";
return(pageContent);
}
I've edited the code. The <h3> line was within the head of the document, now fixed, and I added a style attribute to <body> based on your remark about wanting text centered.
Ok, your code contains errors, because you need to learn how to work with strings and quotes and how to escape quotes.
var str1 = "qwe";
var str2 = "asd";
var str3 = str1 + str2; // will be qweasd
var str3 = str1 + '1111' + str2; // will be qwe1111asd
var str3 = str1 + 'z"1"' + str2; // will be qwez"1"asd
var str3 = str1 + "z\"1\"" + str2; // will be qwez"1"asd. There is no difference if you use double quotes or single. If you use single quotes, all single quotes in the string must be escaped with backslash and opposite with double quotes
// and the same with single quotes:
var str3 = str1 + 'z\'1\'' + str2; // will be qwez'1'asd
also, you are using document.write function, which overrides the content of current page, but you need a new window, which is why we should use function window.open which returns a new window handler. We save it into OpenWindow variable and then we apply our content using OpenWindow.document.write passing our string pageContent as a first parameter
and the correct code:
function myWindow(){
var pageContent, pageTitle;
document.title = "Selected Image Preview";
document.body.style.textAlign="center";
pageContent = "<html><head><title>";
pageContent += pageTitle + "</title>";
pageContent += "<script>alert('The page ' + document.title + ' was created: ' + document.lastModified)</script>";
pageContent += "<h3>Name of Image</h3>";
pageContent += '</head><body align="center"><strong><font color="violet">Here is the image you selected.</font>';
pageContent += "</strong></body></html>";
var OpenWindow = window.open('#','_blank','width=335,height=330,resizable=1');
OpenWindow.document.write(pageContent);
}
pageContent += "<h3>"Name of Image"</h3>";
You don't need quotes around name of image. The entire line should be treated as a String.
pageContent += "<h3>Name of Image</h3>";
Basically, anything in HTML tags doesn't need quotes unless you intend for quotes to appear.
For this line:
pageContent += "</head><body align="center"><strong>" + "<font color= " violet ">"Here is the image you selected. "</font>";
You should use single quotes.
pageContent += "</head><body align='center'><strong>" + "<font color='violet'>Here is the image you selected. </font>";
You should be able to fix the rest of your HTML, keeping in mind single quotes for attributer, no quotes for content.
As to the HTML itself, it should look like this to follow at least intended standards. You should move most of the styles eventually to CSS.
<html>
<head>
<title>Selected Image Preview</title>
<script>// your script here </script>
</head>
<body>
<div align='center'>
<!-- your content here -->
</div>
</body>

Javascript break then back on to print html?

In php, if I'm echoing html I would usually break PHP then turn it back on again. Even if I had one variable in the middle e.g.
echo " ?>
<div class="className">Hello World</div>
<div class="className">it's a <?=$kindOfDay?></div>
<div class="className">day today</div>
<? "; ?>
Is there a way to do something similar in javascript? To allow me an easier way to write e.g.
html += '<div class="className">Hello World</div>';
html += '<div class="className">it\'s a ' + kindOfDay + '</div>';
html += '<div class="className">day today</div>';
Maybe this?
html = '<div class="className">Hello World</div>' +
'<div class="className">it\'s a great</div>' +
'<div class="className">day today</div>';
Arrays are the best for this, Try:
var kindOfDay = 'great',
html = ['<div class="className">Hello World</div>',
'<div class="className">it\'s a '+ kindOfDay + ' great</div>',
'<div class="className">day today</div>'].join('');
You could put the three elements into a single string, but there is not really any easier way to write it.
Edit:
To use a multi-line string in javascript, you can do
html +=
"This \
is \
a \
sentence.";
Keep in mind that some browsers will insert newlines, and some wont.

Uncaught SyntaxError: Unexpected identifier with .append() string

I keep getting this error in the $('#savetickets-list') line. I want to dynamically add fields to a table, the table has the id in HTML.
<div class="savetickets-list">
</div>
In javascript I fill the table in a for loop
for (var i = 0; i < len; i++) {
// the data comes from a web database
var ticketname = results.rows.item(i).iTicketName;
$('#savetickets-list').append('
<div class="saveticket gradient-top">
<h3>' + ticketname + '</h3>
</div>
');
}
I dont know how to solve this. jQuery is loaded, I also checked the name of the selector.
Please help.
$('#savetickets-list').append('\
<div class="saveticket gradient-top">\
<h3>' + ticketname + '</h3>\
</div>\
');
when you want to write multiline strings in JS, you must escape new lines.
It is because you are using new lines.
JS does not automatically read new lines for you. It treats them as new statements.
The way I prefer to do this is like:
$('#savetickets-list').append('<div class="saveticket gradient-top">'+
'<h3>' + ticketname + '</h3>'+
'</div>');
Just checked.
The problem is in the newlines, you have to concatenate strings or put all the statement in a single line.

Categories