Sarkis Arutiunian Sarkis Arutiunian - 5 months ago 26
Javascript Question

$.get() and fetch() getting HTML body

I stuck with one small issue. Rewriting js file from jQuery to native JS, and in jQuery we use:

$.get(`/page`, function (data) {
elem.html(data);
}


basically we fetching body from '/page' and pushing it to elem.innerHTML.

But how I can get html body using fetch() instead of .get()?

Answer

This looks like the equivalent:

fetch('/page').then(function(response) {
    return response.text();
}).then(function(string) {
    elem.innerHTML = string;
});

fetch() returns a promise that resolves to a Response object. The text() method of the Response returns a promise that resolves to the body of the response as a string. You then put that string into the HTML.

DEMO