问题描述
是否有办法从另一个HTML文件中获取DOM元素,而不是从调用JS文件的HTML文件中获取元素?
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模板,并将其呈现在主html文件中,具体取决于JS文件施加的某些条件。
My idea is to make html templates, and render them in a main html file, depending on certain conditions imposed by the JS file.
类似
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>
这是远程文件的内容:
<!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.
这篇关于使用JS从其他HTML文件访问DOM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!