Here is an alternative that requires no external libraries of any sort; just vanilla HTML and JS.
<script>
fetch('https://example.com/webpage-url') // Include the complete URL to the webpage featuring the div of interest.
.then(response => response.text())
.then(html => {
let parser = new DOMParser();
let doc = parser.parseFromString(html, 'text/html');
let divToEmbed = doc.querySelector('#target-div-id'); // See Note A.
let container = document.getElementById('container'); // See note B.
container.appendChild(divToEmbed);
})
.catch(error => console.error(error));
</script>
<div id="container"><!-- Leave empty; imported div goes here. --></div>
Because the code doesn't exploit any external tools, it is rather bulky, so you might want to include it in a separate file and link that to your HTML document: <script src="script.js"></script>
Note A. If the div you're trying to embed from another website doesn't have an ID, just use one of its classes as long as no other div in the webpage document also has that same class name. If the only classes available are shared by other divs, narrow down your query by selecting more class names. To do that, you should not separate the class names using commas, but rather string them together without spaces, e.g. .class1.class2.class3
. This ensures that only the div which is in all of those classes will be selected.
Note B. You can rename "container" to whatever you want, as long as the placeholder div in your HTML has a consistent ID. You could also use a class name, by replacing getElementById
with getElementByClassName
. I recommend using IDs for this type of stuff, though.
Note C. If the website you're importing your div from does not allow CORS (Cross-Origin Resource Sharing), this solution will not work.