Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

163
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!