Tompina Tompina - 4 years ago 78
HTML Question

text/template inside js-file?

I want to move this code from my html-file to a js-file, is there any smooth way to do this without having to put the HTML-code as a string?

<script type="text/template" id="template_test">
<h4>Test</h4>
<p>blablabla</p>
</script>


Thanks!

Answer Source

You can use the createElement function to create HTML elements however if you intend to move alot of code you should consider using a templeting engine.

// Create the <h4> element
var heading = document.createElement("h4"); 

// add the text    
heading.textContent = "TEST";

// Create the text node <p>       
var p = document.createTextNode("blablabla");  

//get the element to which you want to append the h4 and p
var container = document.getElementById("myID");

// Append h4 and p 
container.appendChild(heading);
container.appendChild(p);          
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download