¿Es esto posible, y si es así, cómo se hace?
No quiero usar iframes.
Quiero escribir el html de solo un div
en un archivo separado. Luego quiero insertar esto en mi body
de mi html.
Luego quiero escribir un archivo js separado que opere el código en el div
.
Entonces mi archivo html se vería así:
mydivhtml.html
(Es solo este html, sin encabezados ni cuerpo, etc.)
<div id="mydivhtml" style="width: 30vw; height: 100vh;"> <button id="myButton" onclick="MyOnClick();"></button> <label id="myLabel"></label> </div>
Mi archivo js sería un archivo js normal:
mydivjs.js
function MyOnClick(){ document.getElementById("myLabel").innerHTML = "Hello"; }
Luego, cuando quise usar esto, incluí el archivo js como de costumbre:
<script type="text/javascript" src="mydivjs.js"></script>
Pero , luego solo agrego el html de alguna manera.
Sé que la gente aconseja no hacer document.body.innerHTML = document.body.innerHTML + "<div>Hello!</div>";
porque seguirá disparando onload
.
Así que quiero hacer algo como esto:
var myDiv = document.createElement("div"); myDiv.id = 'mydivhtml'; myDiv.innerHTML = "<button id=\"myButton\" onclick=\"MyOnClick();\"></button>" "<label id=\"myLabel\"></label>"; document.body.appendChild(myDiv);
PERO , ¿cómo haces esto solo desde mydivhtml.html
sin tener que escribirlo poco a poco?
Entonces, si sus directorios son así
Main -| |main.html |mydivhtml.html |mydivjs.js
entonces deberías tener este código en tu 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); // need to have mydivjs.js as a script var mydivjs = document.createElement("script") mydivjs.src ="./mydivjs.js" myDiv.appendChild(mydivjs) }) </script>
espero que funcione...