Equivalent to $.fn.load without jQuery
Asked Answered
V

3

28

I want to load some Jade content into a certain div on button click. I have found how to do this with jQuery, there are several posts on it, and essentially what I want to do is

$('#div').load('/somePage');

However, I am unable to use jQuery in my project. Is there an equivalent function in vanilla JavaScript?

Vyatka answered 30/6, 2016 at 20:18 Comment(3)
"Vanilla JavaScript" doesn't have any provisions for anything like ajax. Browsers have the old XMLHttpRequest API and newer ones support the fetch() API.Kerril
You can find similar thing in youmightnotneedjquery.comPawpaw
Also see the fetch API.Indication
K
47

I think you can do this with the following;

var request = new XMLHttpRequest();

request.open('GET', '/somepage', true);

request.onload = function() {
  if (request.status >= 200 && request.status < 400) {
    var resp = request.responseText;

    document.querySelector('#div').innerHTML = resp;
  }
};

request.send();

By the way, you can do this with fetch API too.

fetch('/somepage')
  .then(function(response) {
    return response.text();
  })
  .then(function(body) {
    document.querySelector('#div').innerHTML = body;
  });

By the way, you can read this blog post for learning something about fetch API.

Kunming answered 30/6, 2016 at 20:34 Comment(7)
Note: fetch is not supported by any of the IE versions, the latest Safari and the latest Firefox. developer.mozilla.org/en-US/docs/Web/API/…Mississippian
@JonathanLaliberte I don't think ReadableStream is necessary for such a case. So I'd say all modern browsers (except IE) support it. Besides that, there is a polyfill for the browsers which don't support Fetch. github.com/github/fetchKunming
great start, but we're missing the part where we can specify a subset of the returned page. I found a start on that bit in a separate thread.Hospitalize
I get document is not definedHallowell
@Hallowell could you please post a new question with some code snippets you have in use?Kunming
hey, thanks for responding. I just realised you have this in your client side js file, right? I was trying to write it in my node.js server file. I have a version of this working nowHallowell
Yes, this code is designated for browsers. As there is no DOM available on the server-side, this snippet will not be directly working.Kunming
C
6

While I was trying to solve the same problem, I made this which is based on Ali BARIN's answer, and seems to work great but is a bit more explicit version, adding init information, and has some logic to use document.getElementById instead of querySelector.

/*
 * Replicates the functionality of jQuery's `load` function, 
 * used to load some HTML from another file into the current one.
 * 
 * Based on this Stack Overflow answer:
 * https://mcmap.net/q/490107/-equivalent-to-fn-load-without-jquery
 * And `fetch` documentation:
 * https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch
 * 
 * @param {string} parentElementId - The ID of the DOM element to load into
 * @param {string} htmlFilePath - The path of the HTML file to load
 */
const loadHtml = function(parentElementId, filePath) {
    const init = {
        method : "GET",
        headers : { "Content-Type" : "text/html" },
        mode : "cors",
        cache : "default"
    };
    const req = new Request(filePath, init);
    fetch(req)
        .then(function(response) {
            return response.text();
        })
        .then(function(body) {
            // Replace `#` char in case the function gets called `querySelector` or jQuery style
            if (parentElementId.startsWith("#")) {
                parentElementId.replace("#", "");
            }
            document.getElementById(parentElementId).innerHTML = body;

        });
};
Cacilie answered 17/3, 2018 at 20:12 Comment(1)
How do you access document in document.getElementById(parentElementId).innerHTML = body from server side? I get document is not defined..Hallowell
V
0

You can do it like that, but there is something you'll have to pay attention to it.

const getData = (url) => {
  return new Promise((resolve, reject) => {
    let request = new XMLHttpRequest();
    request.onload = function () {
      if (this.readyState === 4 && this.status === 200) {
        resolve(this.responseText);
      } else {
        reject(this.responseText);
      }
    };
    request.open("get", url, true);
    request.send();
  });
};

getData("Your URL")
  .then((resolve) => {
    console.log(resolve);
  })
  .catch((reject) => {
    console.error(reject);
  });

What I want you to pay attention to is if you put URL to a page it will return it from <html> to </html> as string, I guess there is no way to get just apart from it like method .load() in jQuery.

Valles answered 25/12, 2021 at 12:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.