简体   繁体   中英

Access DOM from a different html file with JS

Is there a way to get the DOM elements from another HTML file rather than the elements from the HTML file that calls the JS file?

My idea is to make html templates, and render them in a main html file, depending on certain conditions imposed by the JS file.

Something like

 var initScreen = new document(URL); document.getElementById("body") = initScreen.getElementById("body"); 

supposing that this is the correct way.

Yep. You can fetch a remote (or local) file and then use createHTMLDocument :

 document.querySelector(".the_replacer").addEventListener("click", () => { fetch("https://cdn.rawgit.com/ryanpcmcquen/c22afdb4e6987463efebcd495a105d6d/raw/476e97277632e89a03001cb048c6cacdb727028e/other_file.html") .then((response) => response.text()) .then((text) => { const otherDoc = document.implementation.createHTMLDocument("Foo").documentElement; otherDoc.innerHTML = text; document.querySelector(".element_on_main_page").textContent = otherDoc.querySelector(".awesome_external_element").textContent; }); }); 
 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>repl.it</title> <link href="index.css" rel="stylesheet" type="text/css" /> </head> <body> <div class="element_on_main_page">Replace me, please.</div> <button class="the_replacer">Replace them.</button> <script src="index.js"></script> </body> </html> 
https://repl.it/@ryanpcmcquen/TurboTremendousProgramminglanguages

Here's the remote file's contents:

 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>repl.it</title> <link href="index.css" rel="stylesheet" type="text/css" /> </head> <body> <div class="awesome_external_element">Foobar.</div> </body> </html> 

Browser support is not too bad. On the other hand fetch is pretty modern, so if you are going for legacy support you should use XMLHttpRequest .

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