I'm quite sure this a common question, but I'm pretty new to JS and am having some trouble with this.
I would like to load x.html into a div with id "y" without using iframes. I've tried a few things, searched around, but I can't find a decent solution to my issue.
I would prefer something in JavaScript if possible.
Thanks in advance, everyone!
Use the object Tag as an Alternative to Iframe in HTML We can use the object tag in HTML to embed external resources in the webpage. We can use the tag to display another webpage in our webpage. The object tag is an alternative to the iframe tag in HTML.
To load external HTML into a <div>, wrap your code inside the load() function. To load a page in div in jQuery, use the load() method.
Embedding an HTML file is simple. All we need to do is use the common „<link>“ element. Then we add the value „import“ to the „rel“ attribute. Using „href“ we attach the URL of the HTML file, just like we are used to when it comes to stylesheets and scripts.
Wow, from all the framework-promotional answers you'd think this was something JavaScript made incredibly difficult. It isn't really.
var xhr= new XMLHttpRequest(); xhr.open('GET', 'x.html', true); xhr.onreadystatechange= function() { if (this.readyState!==4) return; if (this.status!==200) return; // or whatever error handling you want document.getElementById('y').innerHTML= this.responseText; }; xhr.send();
If you need IE<8 compatibility, do this first to bring those browsers up to speed:
if (!window.XMLHttpRequest && 'ActiveXObject' in window) { window.XMLHttpRequest= function() { return new ActiveXObject('MSXML2.XMLHttp'); }; }
Note that loading content into the page with scripts will make that content invisible to clients without JavaScript available, such as search engines. Use with care, and consider server-side includes if all you want is to put data in a common shared file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With