最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Access DOM from a different html file with JS - Stack Overflow

programmeradmin0浏览0评论

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");

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.

Share Improve this question asked Feb 13, 2018 at 4:00 ekiimekiim 8421 gold badge12 silver badges27 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

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

document.querySelector(".the_replacer").addEventListener("click", () => {
    fetch("https://cdn.rawgit./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.

发布评论

评论列表(0)

  1. 暂无评论