有没有办法从另一个 HTML 文件中获取 DOM 元素,而不是从调用 JS 文件的 HTML 文件中获取元素?
我的想法是制作 html 模板,并根据 JS 文件施加的某些条件在主 html 文件中呈现它们。
有点像
var initScreen = new document(URL);
document.getElementById("body") = initScreen.getElementById("body");
假设这是正确的方法。
最佳答案
是的。您可以获取远程(或本地)文件,然后使用 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还不错。另一方面fetch非常现代,所以如果您要获得遗留支持,您应该使用 XMLHttpRequest .
关于javascript - 使用 JS 从不同的 html 文件访问 DOM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48759219/