Creating HTML Content In a Variable in Javascript - javascript

I have a javascript variable I need to create like this:
var HTMLContent = '<div class="className">HTML Content</div>';
How can I format it in an easier to read format because I'm going to want to create multiple lines of HTML.
e.g.
var HTMLContent = '
<div class="className">
HTML Content
</div>
';
Is something like that possible?
It would also be good if I could import via URL e.g. var HTMLContent = 'http://domain.com/page.html';

var longStr = "You can split\
the string onto multiple lines\
like so";
An example using your HTML would be:
var longStr =
'<div class="className">\
HTML Content\
</div>';
To load external HTML, check out jQuery's load method:
$('#result').load('ajax/test.html');

In your page markup, add a hidden template div, like:
<div id="contentTemplate" style="display: none;">
<div class="className">
HTML_CONTENT
</div>
</div>
...then in your JavaScript, you can do something like:
var newContent = 'The content for the new element';
var templateContent = document.getElementById("contentTemplate").innerHTML;
var htmlContent = templateContent.replace("HTML_CONTENT", newContent);
You could also use an AJAX request to pull the value of newContent from a URL to get your dynamic content loading working. If you plan on doing this, however, then I suggest you investigate using a framework like jQuery, which can greatly simplify this process.

You can also use backticks
function myFunc() {
var HTMLContent =`
<div class="className">
<div>HTML Content</div>
</div>
`;
document.getElementById('demo').innerHTML = (HTMLContent);
}
myFunc()
<div id="demo"></div>

var HTMLContent =
'<div class="className">' +
'HTML Content' +
'</div>';

You can do something like:
var HTMLContent = '<div class="ClassName">' +
'HTML Content' +
'</div>';

You can use escape characters:
var HTMLContent = '<div class="className">\n\tHTML Content\n</div>';
I may have misinterpretted the question, you want the javascript to be more readable, not the html stored in the variable?

var HTMLContent = "" +
"<div class=\"className\">\n" +
" HTML Content\n" +
"</div>\n" +
"";
This way, the script that writes it it pretty and the code it writes will be pretty too if someone were to view-source.

Related

File Structure of a Div Javascript Class

Is this possible, and if so how is it done?
I do not want to use iframes.
I want to write the html of just a div in a separate file. I want to then insert this into my body of my html.
I then want to write a separate js file which operates the code in the div.
So my html file would look like this:
mydivhtml.html (It is just this html, no headers or body etc)
<div id="mydivhtml" style="width: 30vw; height: 100vh;">
<button id="myButton" onclick="MyOnClick();"></button>
<label id="myLabel"></label>
</div>
My js file would be a normal js file:
mydivjs.js
function MyOnClick(){
document.getElementById("myLabel").innerHTML = "Hello";
}
Then when I wanted to use this, I include the js file as normal:
<script type="text/javascript" src="mydivjs.js"></script>
But, then I just add the html in some way.
I know people advise not to do document.body.innerHTML = document.body.innerHTML + "<div>Hello!</div>"; because it will keep on firing onload.
So I want to do something like this:
var myDiv = document.createElement("div");
myDiv.id = 'mydivhtml';
myDiv.innerHTML = "<button id=\"myButton\" onclick=\"MyOnClick();\"></button>"
"<label id=\"myLabel\"></label>";
document.body.appendChild(myDiv);
BUT how do you do this from just the mydivhtml.html without having to write it out bit by bit?
So if your directories is like this
Main -|
|main.html
|mydivhtml.html
|mydivjs.js
then you should have this code on your main.html
<script>
fetch("./mydivhtml.html").then(x=>x.text()).then(data =>{
var myDiv = document.createElement("div");
myDiv.id = 'mydivhtml';
myDiv.innerHTML = data;
document.body.appendChild(myDiv);
// need to have mydivjs.js as a script
var mydivjs = document.createElement("script")
mydivjs.src ="./mydivjs.js"
myDiv.appendChild(mydivjs)
})
</script>
hope it works...

How to display image using javascript dynamically

I have a javascript code and i want to insert an image inside the dynamically created html page. Please correct me if i'm going wrong with the code. the code runs something like this:
var html = [
'<div class="uicomponent-panel-controls-container");">',
'<img src=' + image1 + '>',
'</div>'
].join('\n');
_dockPanel.container.append(html);
Thanks in advance.
You have a typo here: ...container");">'
Here is the working (for demo purpose slightly modified) fiddle:
var image1 = 'https://image.flaticon.com/teams/slug/freepik.jpg';
var html = [
'<div class="uicomponent-panel-controls-container">',
'<img src=' + image1 + '>',
'</div>'
].join('\n');
document.getElementById("dock").innerHTML = html;
<div id="dock"></div>
var html = [...].join('');
html rendering dom does not need to be separated by '\n'

How to wrap a tag around a text inside a tag?

For example I have this piece of code:
<div class="myclass">Hello everybody!</div>
Then I want to wrap a <p> tag around the text to have this:
<div class="myclass"><p>Hello everybody!</p></div>
How can I do this with jQuery?
I tried this:
$('.myclass').text().wrap('p');
But didn't work.
You can do this using .wrapInner():
$('.myclass').wrapInner('<p></p>');
Demo: Fiddle
try something like this
$(function(){
$('.myclass').wrapInner('<p></p>');
})
REFERENCE :
http://api.jquery.com/wrapInner/
Alternative
$(function(){
var txt = '<p>' + $('.myclass').text() + '</p>';
$('.myclass').html(txt);
})
Again to remove p tag
$(function(){
var txt = $('.myclass').text();
$('.myclass').html(txt);
})
A Different approach,
$('.myclass').html('<p>' + $('.myclass').text() + '</p>');
DEMO
To unwrap the tag you simply do like this,
$(".myclass").html($('.myclass > p').text());
DEMO

Inserting javascript global variable in <div> tag in HTML body

I have the following tag in HTML:
<div data-dojo-type="dojox.data.XmlStore"
data-dojo-props="url:'http://135.250.70.162:8081/eqmWS/services/eq/Equipment/All/6204/2', label:'text'"
data-dojo-id="bookStore3"></div>
I have the values 6204 and 2 in a couple of global variables in the script section:
<html>
<head>
<script>
...
var newNeId = gup('neId');
var newNeGroupId = gup('neGroupId');
...
</script>
</head>
</html>
Is it possible to have these variables in the div tag in the HTML body? If so, how?
To clarify this a bit more, I need to have the URL in the tag something like this:
url: 'http://135.250.70.162:8081/eqmWS/services/eq/Equipment/All/'+newNeGroupId+'/'+newNeId
I changed it according to your requirement:
<html>
<head>
<script type="text/javascript">
// example data
var newNeId = 10;
var newNeGroupId = 500;
window.onload = function(e){
var myDiv = document.getElementById("myDiv");
myDiv.setAttribute("data-dojo-props", "url:'http://135.250.70.162:8081/eqmWS/services/eq/Equipment/All/" + newNeId + "/" + newNeGroupId + "', label:'text'");
}
</script>
</head>
<body>
<div id="myDiv" data-dojo-type="dojox.data.XmlStore"
data-dojo-props="url:'http://135.250.70.162:8081/eqmWS/services/eq/Equipment/All/6204/2', label:'text'"
data-dojo-id="bookStore3"></div>
</body>
</html>​
You could add them to the <div> using the same datalist pattern (MDN docu) as Dojo:
<div id="savebox" data-newNeId="6204" data-newNeGroupId="2"></div>
These attributes are then accessible by the element.dataset.itemName.
var div = document.querySelector( '#savebox' );
// access
console.log( div.dataset.newNeId );
console.log( div.dataset.newNeGroupId );
As #EricFortis pointed out, the question remains, why you want to do this. This only makes sense, if you pass those values on from the server side.
Take one parent div then set its id and then you can rewrite whole div tag with attributes using innerHTML.
document.getElementById('id of parent div').innerHTml="<div data-dojo-type=/"dojox.data.XmlStore/"
data-dojo-props=/"url:'http://135.250.70.162:8081/eqmWS/services/eq/Equipment/All/6204/2', label:'text'/"
data-dojo-id=/"bookStore3/"></div>";
you can append values you wants in innerhtml now.
here's simple native js code to do it
var body = document.getElementsByTagName('body')[0];
var myDiv = document.createElement('div');
myDiv.setAttribute('id', 'myDiv');
var text = 'newNeId: ' + newNeId +
'<br/> newNeGroupId: ' + newNeGroupId';
body.appendChild(myDiv);
document.getElementById('myDiv').innerHTML = text;

remove CoffeeScript anonymous function calls

buildIMG = (src, resize) ->
html = '<div class="left"><div class="foods_image">'
html += '<a onclick="popitup("http://somewhere.com/test" href="javascript:void(0)">'
html += ' <img src="'+src+'" '+resize+' />'
html += '</a>'
html += '</div></div>'
html
popitup = (url) ->
newwindow=window.open(url,'name','height=640,width=640')
newwindow.focus() if window.focus
false
I currently have a bookmarklet that inserts javascript code(the one above) into a website. I wrote the above coffeescript and it generates this:
(function() {
var buildIMG, popitup;
buildIMG = function(src, resize) {
var html, nbsp;
html = '<div class="left"><div class="foods_image">';
html += '<a onclick="popitup(\'http://somewhere.com/test\');" href="javascript:void(0)">';
html += ' <img src="' + src + '" ' + resize + ' />';
html += '</a>';
html += '</div></div>';
return html;
};
popitup = function(url) {
var newwindow;
newwindow = window.open(url, 'name', 'height=640,width=640');
return newwindow.focus()(window.focus ? false : void 0);
};
}).call(this);
I snipped the functions that uses buildIMG. That function creates an overlay over the site and displays all images in that overlay. buildIMG is called for each image to create the html.
The problem is that the onclick="popitup("http://somewhere.com/test" portion doesn't work. It is undefined.
A solution I did was to remove this which was generated by CoffeeScript:
(function() {
}).call(this);
It was fixed as soon as I removed that. How do I not have CoffeeScript put in those lines in my generated javascript?
CoffeeScript allows to compile JavaScript without this safety wrapper by --bare option.
Although suppressed within this documentation for clarity, all
CoffeeScript output is wrapped in an anonymous function: (function(){
... })(); This safety wrapper, combined with the automatic generation
of the var keyword, make it exceedingly difficult to pollute the
global namespace by accident.
It's from CoffeScript site.
If you want to create a global method or variable you need to
root = this
localProperty = "111"
root.property = localProperty
And then you'll get a property in global scope.

Categories

Resources