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?
CodePudding user response:
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);
})
</script>
hope it works...