Sarkis Arutiunian Sarkis Arutiunian - 3 months ago 12x
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) {

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

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


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.