I'm trying to implement the includeHTML() function provided by w3schools.
https://www.w3schools.com/howto/howto_html_include.asp
It works properly if I manually create a div, like in the site:
<div w3-include-html="awebsite.html"></div>
However if I try to create a div with Javascript then it is not working, for example:
var htmlIncluder = document.createElement("div");
htmlIncluder.setAttribute("w3-include-html", "awebsite.html");
document.body.appendChild(htmlIncluder);
Is it because the div does not have the w3-include-html attribute by default? What should I do to make this work?
Thanks for help!
Update, this is my index.html, to make it more clear in which order things appear, it also shows the includeHTML function:
<script>
function includeHTML() {
var z, i, elmnt, file, xhttp;
/*loop through a collection of all HTML elements:*/
z = document.getElementsByTagName("*");
for (i = 0; i < z.length; i++) {
elmnt = z[i];
/*search for elements with a certain atrribute:*/
file = elmnt.getAttribute("w3-include-html");
if (file) {
/*make an HTTP request using the attribute value as the file name:*/
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4) {
if (this.status == 200) {elmnt.innerHTML = this.responseText;}
if (this.status == 404) {elmnt.innerHTML = "Page not found.";}
/*remove the attribute, and call this function once more:*/
elmnt.removeAttribute("w3-include-html");
includeHTML();
}
}
xhttp.open("GET", file, true);
xhttp.send();
/*exit the function:*/
return;
}
}
}
</script>
</head>
<body>
<!--this is the manually created div that works-->
<div w3-include-html="2.html"></div>
<!-- divs created with js.js have the correct attribute but don't show any content -->
<script src="js.js"></script>
<script>
includeHTML();
</script>
</body>
Here's the part where the js.js creates the div that should contain the includeHTML(); content. The div is added to a cell that is added to a grid, and the whole thing is added to the document.body. It's visible in the site so it correct, for example the text element "middle" is visible. The page is divided to header, middle and footer as a grid all of that is also visible.
cell.className = "middle";
cell.id = "middle-"+cellIdNo;
var text = document.createTextNode("middle");
var htmlIncluder = document.createElement("div");
htmlIncluder.setAttribute("w3-include-html", "2.html");
cell.appendChild(text);
cell.appendChild(htmlIncluder);