Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

164
Vistas
File Structure of a Div Javascript Class

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?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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);
    // need to have mydivjs.js as a script
    var mydivjs = document.createElement("script")
    mydivjs.src ="./mydivjs.js"
    myDiv.appendChild(mydivjs)
})

</script>

hope it works...

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda