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.
Related
I'm using javascript to add html to my 's.
I made a loop that goes around all projects there are. There are multiple projects and in every project there are multiple pictures.
The first part creates the first projecttitle within a div that gets an id(the projectname) and the first pictures.
$( ".projectbeeldcontainer" ).append(
'</div>'+
'<h1 class="projecttitel" id="'+name+'">'+name+'</h1>'+
'<div class="row dashboardrow" id="'+name+'id">'+
'<div class="col-sm-2">'+
'<div class="thumbnail">'+
'<a href="/w3images/lights.jpg">'+
'<img src="projectbeelden/'+name+'/'+decodeURI(image)+'" class="img-rounded">'+
'</a>'+
'<div class="caption tags">'+
'<p>titel van project</p>'+
'</div>'+
'</div>'+
'</div>';
);
After this, the script will check if the projectname of the next image allready exists. If it does exist (because we added it with the code above), then it will insert a new div inside of the project div we created:
document.getElementById(name+'id').append(
'<div class="col-sm-2">'+
'<div class="thumbnail">'+
'<a href="/w3images/lights.jpg">'+
'<img src="projectbeelden/'+name+'/'+decodeURI(image)+'" class="img-rounded">'+
'</a>'+
'<div class="caption tags">'+
'<p>titel van project</p>'+
'</div>'+
'</div>'+
'</div>'
);
The problem i have now is that the first line of code successfull creates the div's and the image. The second code works for 98%.
It does recognise the div with the id and puts the content in it. But the problem is that it adds quotes before my first line and after. So it looks like it thinks it's a string and not html.
So it literally adds "<div ..." on my page.
Can anyone help me please? Sorry for the bad spelling and grammar.
Use innerHTML instead of append.
document.getElementById(name+'id').innerHTML += "<div> put your html </div>";
Append adds a textNode. Better way is something like this by generating it and inserting into the DOM:
var el = document.createElement("div");
el.appendChild(document.createTextNode("Put yout HTML"));
document.getElementById(name+'id').appendChild(el);
The problem is that you are literally telling it to append a string to the DOM, you are not creating an element that you can insert.
If you wrap the html that you are trying to append in the jQuery wrapper $('<div class="col-sm-2">....</div>');, then it will be treated by jQuery as an a jQuery object and should then be able to be inserted in the manor that you need.
This work to me
var stringToHTML = function (str) {
var parser = new DOMParser();
var doc = parser.parseFromString(str, 'text/html');
return doc.body;
};
$( ".projectbeeldcontainer" ).append(stringToHTML('<p>text</p>'))
DEMO
var insertData = '<div class="col-sm-2">'+
'<div class="thumbnail">'+
'<a href="/w3images/lights.jpg">'+
'<img src="" class="img-rounded">'+
'</a>'+
'<div class="caption tags">'+
'<p>titel van project</p>'+
'</div>'+
'</div>'+
'</div>';
document.getElementById('a').innerHTML = insertData;
<div id="a"></div>
You can just use < and > instead of "<" and ">" in your code. Browser will not recognize this string as html code and print it as a plain text.
With my append(html) code I would like to be able to include <script></script>
Question: How can I use the <script></script> will not allow me to add them.
As you can see at bottom of addContent() i need to include $("#page_code[' + content_row + ']").summernote({height: 300});
Script
<script type="text/javascript">
var content_row = <?php echo $content_row; ?>;
//$(document).ready(function() {
// $('#page_code').summernote({height: 300});
//});
function addContent() {
html = '<div id="content-row">';
html += '<div class="form-group">';
html += '<label class="col-sm-2">Page Content Name</label>';
html += '<div class="col-sm-10">';
html += '<input type="text" class="form-control" name="page_code[' + content_row + '][name]" placeholder="Page Content Name">';
html += '</div>';
html += '</div>';
html += '<div class="form-group">';
html += '<label class="col-sm-2">Page Content</label>';
html += '<div class="col-sm-10">';
html += '<textarea class="form-control" id="page_code[' + content_row + ']" name="page_code[' + content_row + '][code]" style="height: 300px;"></textarea>';
html += '</div>';
html += '</div>';
html += '<script>$("#page_code[' + content_row + ']").summernote({height: 300});</script>';
html += '</div>';
$('#content-row').append(html);
content_row++;
}
</script>
First of all when you are closing your script tag in the string ->
"</script>"
this is an error because "/" in strings is used for escaping, so when closing your tag you should do it
"<//script>"
Second of all - your addContent function is not called?
Jquery provide the html() method that allows you to append, in the given html element, some html. So, you can try with this : http://api.jquery.com/html/
Then, there are some confusions in the part of code that is the reason of your problem:
html += '<script>$("#page_code[' + content_row + ']").summernote({height: 300});</script>';
I think that your selection with "#page_code[..]" for an id is wrong. Because you don't have any element with this id, but with the name attribut "page_code[...]". So, even if your tag will be evaluate, your code seems to be wrong.
To select a tag by his name attribut, you can deal with a specific jquery selector : http://api.jquery.com/attribute-equals-selector/
I hope this will help you.
I have a looong string of HTML inside a Javascript.
Is there any way I can auto indent it?
The conventional way in Sublime Text (pressing F12) won't work because Sublime doesn't know it's HTML.
Here's a portion of it:
'<ul class="obj-ul">' +
'<li ng-repeat="(key, val) in argVal">' +
'<p class="arg-key">{{key}}</p>' +
'<span class="arg-colon">:</span>' +
'<div ng-if="utils.isPrimitive(val)" class="inline-block">'+
'<p ng-click="editVal=!editVal" ng-show="!editVal" class="arg-val">{{argVal[key]}}</p>' +
'<input ng-show="editVal" ng-model="argVal[key]" ng-blur="editVal=!editVal" class="arg-val" />' +
'</div>'+
'<div ng-if="!utils.isPrimitive(val)" class="inline-block">'+
'<rapid-args arg-val="argVal[key]"></rapid-args>' +
'</div>'+
'</li>' +
'<div ng-if="utils.showButtons.showButtonInObject(templateArgVal)">' +
'<button ng-click="vars.show_addObjectItem=!vars.show_addObjectItem">+</button>'+
'<div ng-if="vars.show_addObjectItem" class="add-item">'+
'<input ng-model="newKey" type="text" class="arg-key"/>'+
'<span class="arg-colon">:</span>' +
'<div id="new-value">'+
'<div ng-if="!vars.show_addObjectValue" class="value-types">'+
'<p ng-click="objects.addItem(argVal, newKey, \'array\'); vars.show_addObjectItem=!vars.show_addObjectItem" class="value-types-type">Array</p>'+
'<p ng-click="objects.addItem(argVal, newKey, \'object\'); vars.show_addObjectItem=!vars.show_addObjectItem" class="value-types-type">Object</p>'+
'<p ng-click="vars.show_addObjectValue=!vars.show_addObjectValue" class="value-types-type">String</p>'+
'<p>{{showValInput}}</p>' +
'</div>' +
'<div ng-if="vars.show_addObjectValue">'+
'<input ng-model="newVal" type="text" class="arg-key"/>'+
'<button ng-click="objects.addNewKeyVal(argVal, newKey, newVal); vars.show_addObjectValue=!vars.show_addObjectValue">✓</button>'+
'<button ng-click="vars.show_addObjectValue=!vars.show_addObjectValue">Cancel</button>'+
'</div>' +
'</div>' +
'</div>' +
'</div>'+
'</ul>' +
Sort of what Mouser suggested in a comment, you're going to have to remove the apostrophe's and plus signs from this code using a find+replace tool (notepad++ has one, I'm sure sublime will have one too) then do your formatting thing with F12 in sublime and then re-add your apostrophe's and plus signs using regex.
Here's a demonstration of how to remove your string formatting using Notepad++ (or any Regex based find and replace string manipulator):
Find What: '(.*?)'[\s]?\+
Replace With: $1
To add them back again after you've formatted you can simply do:
Find What: (.*)
Replace With: '$1' +
Here's a way:
Remove all the quotes and + used to concatenate the different lines, i.e., make it a single string (you may use search-replace -> replace all) without any + in between to join.
Copy the resulting string and paste at http://www.freeformatter.com/html-formatter.html or any other online html formatter.
Copy the result and paste it back.
Hope it helps.
I am trying to add this HTML/JavaScript code into a jQuery variable. I've managed to insert double quotes by writing is with a backshlash \", however the same tactic didn't work for the single quotes:
ajaxData += '<div class=\"menu-item-' + $(this).attr('div') + 'onclick=\"alert('Jquery Function');\"></div>';
Specifically, this part onclick=\"alert('Jquery Function');
Anyone know how I can go around this?
See this, its beautiful:
ajaxData += '<div class="menu-item-' + $(this).attr('div') + ' onclick="alert(\'Jquery Function\');"></div>';
Dirty escape pheeww...Try this
ajaxData += '<div class="menu-item-' + $(this).attr('div') + 'onclick="alert(\'Jquery Function\');"></div>';
ajaxData += '<div class="menu-item-' + $(this).attr('div') + 'onclick="alert('Jquery Function');"></div>';
add escape \ for single quotes. if your string is within single quotes then you can use double quotes without escape but if using single quotes within single quote then you have to insert escape character
This is are you trying to do?
$var = "ajaxData += '<div class=\"menu-item-' + \$(this).attr('div') + '" onclick=\"alert(\'Jquery Function\');\"></div>';"
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>
`