简体   繁体   中英

get html file from href and load it into the page using vanilla javascript

Let's say I have this menu:

 <div class="dropdown-menu pull-left" aria- labelledby="dropdownMenuButton"> <a class="dropdown-item tuning-selection" id="guitar_standard" href="tunings/guitar_standard.html">Guitar(Standard)</a> <a class="dropdown-item tuning-selection" id="guitar_drop_d" href="tunings/guitar_drop_d.html">Guitar(Drop D) </a> <a class="dropdown-item tuning-selection" id="bass_standard" href="tunings/bass_standard.html">Bass Standard</a> <a class="dropdown-item tuning-selection" id="mandolin_standard" href="tunings/mandolin_standard.html">Mandolin</a> </div>

How could I load those HTML files into a separate div (with no page refresh) via Vanilla JS? I know jQuery is easier but I want to learn how to do it with Vanilla JS.

You can use <link> element with rel attribute set to "import" to load the document fragments before click on element in document.body , and set content of <div> to cloned element of link.import #document .

 <link rel="import" href="data:text/html,<div><h1>guitar standard</h1></div>" id="guitar_standard"> <div class="dropdown-menu pull-left" aria- labelledby="dropdownMenuButton"> <a class="dropdown-item tuning-selection" href="#guitar_standard">Guitar(Standard)</a> </div> <div id="content"></div> <script> const content = document.getElementById("content"); const links = document.links; const imports = document.querySelectorAll("link[rel=import]"); for (const link of links) { link.onclick = (e) => { e.preventDefault(); e.stopImmediatePropagation(); const clone = document.querySelector(e.target.hash).import .querySelector("div").cloneNode(true); content.appendChild(clone); } } </script>

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