I need the equivalent of .load() to JS
22,573
Solution 1
UPDATE:
Using Fetch API with .then()
function load(url, element)
{
fetch(url).then(res => {
element.innerHTML = res;
});
}
Old XMLHttpRequest
function load(url, element)
{
req = new XMLHttpRequest();
req.open("GET", url, false);
req.send(null);
element.innerHTML = req.responseText;
}
Usage
load("x.html", document.getElementById("b"));
Solution 2
If you want to do it without JS, I think this will help you, add this inside #b
<iframe src="x.html"></iframe>
Solution 3
UPDATE:
Using Fetch API with .then()
function load(url, element)
{
fetch(url).then(res => {
element.innerHTML = res;
});
}
Old XMLHttpRequest
function load(url, element)
{
req = new XMLHttpRequest();
req.open("GET", url, false);
req.send(null);
element.innerHTML = req.responseText;
}
Usage
load("x.html", document.getElementById("b"));
This will load "x.html" and put it inside the element.
Related videos on Youtube
Author by
Admin
Updated on July 24, 2020Comments
-
Admin over 3 years
I'm developing a script but I mustn't use jQuery library so I need the equivalent of .load() in JS.
I need to do this without jQuery:
$(document).ready(function(){ $('#a').click(function(){ $('body').append('<div id="b"></div>') $('#b').load('x.html') }); });
Thanks!
-
Ben McCormick over 10 years"I need to do this without JS" I assume you mean without jQuery?
-
-
eeadev over 8 yearswhat if I want the async version of this function?
-
Akshay Gaur about 5 yearsCould you maybe expand on your answer? Or maybe write a short snippet that shows what you are trying to say here?
-
g-otn almost 5 years@eeadev, It's async by default, so you can simply remove the
false
fromreq.open()
or change it totrue
. See XMLHttpRequest.open() -
Danial almost 3 yearsnote that jquery load will execute js on the loaded page (just like you loaded a page into a frame), whereas just setting the html will not