简体   繁体   English

使用JS从其他HTML文件访问DOM

[英]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? 有没有办法从另一个HTML文件中获取DOM元素,而不是从调用JS文件的HTML文件中获取元素?

My idea is to make html templates, and render them in a main html file, depending on certain conditions imposed by the JS file. 我的想法是制作html模板,并将其呈现在主html文件中,具体取决于JS文件施加的某些条件。

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 : 您可以获取一个远程(或本地)文件,然后使用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 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 . 另一方面, fetch非常现代,因此,如果要使用旧版支持,则应使用XMLHttpRequest

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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