简体   繁体   中英

Multiple HTML files connected to one JS file?

So if I have multiple HTML files connected to one JS file, when I run a code that uses the document keyword, does the code know which document I'm referring to? For example, in one of the HTML files, I have a div with the id of main in the body tag and in the js file, I created a new div to append to that specific html file. The code in the js file is basically var div = document.createElement("div") followed by document.getElementById("main").appendChild(div). My question basically is, does the code know which html file to append the div to and which html file to use when i use getelementbyid? If not, how do I specify this if I have multiple html files connected to one js file?

As long as you specify the ids of the divs you want to change, it should work.

The js could be like this:

var div1 = document.createElement("div")
document.getElementById("id1").appendChild(div1); //matches to div1 in the html

var div2 = document.createElement("div");
document.getElementById("id2").appendChild(div2).  //matches to div2 in the html

var div3 = document.createElement("div")
document.getElementById("id3").appendChild(div3).  //matches to div3 in the html

The html could be like this:

<div id="id1"></div>

<div id="id2"></div>

<div id="id3"></div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM