Is there a way to add the contents of one HTML file (the complete file including the tags and all) into a div? A way which uses pure JavaScript? Or is the only way to append lots of elements individually and make it a function maybe?
-
Easy. Make ajax request, append loaded string where you need.dfsq– dfsq2017-12-11 09:20:43 +00:00Commented Dec 11, 2017 at 9:20
-
It's very easy to do without jQuery, but if the HTML to be inlined is valid, it will contain <html> <head> and <body> elements that you shouldn't insert into another HTML document.Touffy– Touffy2017-12-11 09:23:48 +00:00Commented Dec 11, 2017 at 9:23
-
@Touffy hmm... well I can skip that it seems and thank you for the response!😄BK1603– BK16032017-12-11 09:32:37 +00:00Commented Dec 11, 2017 at 9:32
-
@dfsq I only have the front end and I am just starting outBK1603– BK16032017-12-11 09:33:25 +00:00Commented Dec 11, 2017 at 9:33
Add a comment
|
3 Answers
You can do this with ajax...but there is a catch. The HTML you load should not have <html> or <head> tags etc...
Main page:
<html>
<head>
<title>Ajax Wizardry</title>
<script>
function ajax(requestedForm,target) {
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById(target).innerHTML=xmlhttp.responseText;
console.log("Content Updated");
}
console.log("ajax status: "+xmlhttp.status);
}
xmlhttp.open("GET",requestedForm,true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("action=fetch");
}
</script>
</head>
<body>
<input type='button' value='Ajax Magic' onclick='ajax(`stufftoloadintodiv.html`,`target_1`)' />
<div id='target_1'></div>
</body>
</html>
stufftoloadintodiv.html contents
<p style='color:red;'>Hello World</p>
What I have done here is create a function called 'ajax' that accepts 2 variables. The first is the path to the file you want to load, the second is the intended target element id. So if you had <div id='biscuits'></div> and you wanted to load the contents of 'digestive.html' then you would just need to call ajax('digestive.html','biscuits')
Comments
a.html:
<html>
<body>
<h1>Put here your HTML content before insertion of b.js.</h1>
...
<script src="customscript.js"></script>
...
<p>And here whatever content you want afterwards.</p>
</body>
</html>
customscript.js:
document.write('\
\
<h1>Add your HTML code here</h1>\
\
<p>Notice however, that you have to escape LF's with a '\', just like\
demonstrated in this code listing.\
</p>\
\
');