Suppose you have some JavaScript (with JQuery) code that adds some HTML to an existing page, like:
var span = "<span>Text</span>";
some_div_element.append(span);
Is there any way to do this without having the span hard coded? If I want to add a big portion of code, it just doesn't seem right to have it hard coded in the middle of JavaScript code.
-
1You could look into some templating languages, such as handlebarsjs.com HandlebarsPete TNT– Pete TNT2015年06月13日 17:11:09 +00:00Commented Jun 13, 2015 at 17:11
-
2You could store the HTML in a file and load it dynamically. See: api.jquery.com/loadSparky– Sparky2015年06月13日 17:12:09 +00:00Commented Jun 13, 2015 at 17:12
4 Answers 4
It is fairly easy actually with the jquery load function
<html>
<head>
<script src="jquery.js"></script>
<script>
$(function(){
$("#includehtml").load("loadme.html");
});
</script>
</head>
<body>
<div id="includehtml"></div>
</body>
</html>
This way you can have your extra html in a different html file, and just load it in with the load function. The html can be as short or long as you would like without bloating your original page. loadme.html would need to be stored in the same path on the server in this case.
1 Comment
From the jQuery .append() docs, you can pass .append() a jQuery element, like this:
$("#some_div_element").append( $("span") );
With this functionality, you can easily build your span element somewhere in your HTML with display:none and then get/edit/append it in your Javascript code.
1 Comment
If you don't want to insert the html directly than what you can do is create elements using javascript and then apply there properties separately. However, you will have to write a lot of code. Unless you are planning to reuse the elements i think you should stick with inserting the html directly. Its simpler and more efficient.
Here is an example code:
var btn = document.createElement("BUTTON"); // Create a <button> element
var t = document.createTextNode("CLICK ME"); // Create a text node
btn.appendChild(t); // Append the text to <button>
document.body.appendChild(btn);
1 Comment
create re-usable functions then?
function getMeSpan(myText) {
var span = document.createElement('span');
span.innerText = myText;
return span;
};
someOtherDIV.appendChild(getMeSpan('hello'));
someOtherDIV.appendChild(getMeSpan('world!'));