How do I apply Fetch HTML and apply it directly to the DOM?

  • Page Owner: Not Set
  • Last Reviewed: 2022-04-07

I'm returning Html via AJAX and need some JS code to apply it to the DOM.


Answer

Below are two methods you can use to quickly grab and set HTML.

function GetAndReplace(url, element) {
  return fetch(url, {
    headers: {
      "Content-Type": "application/json",
      Accept: "text/html",
    },
    method: "GET",
  })
    .then((x) => x.text())
    .then((x) => {
      element.innerHTML = x;
    });
}
function PostAndReplace(url, element, payload) {
  return fetch(url, {
    headers: {
      "Content-Type": "application/json",
      Accept: "text/html",
    },
    method: "POST",
    body: JSON.stringify(payload),
  })
    .then((x) => x.text())
    .then((x) => {
      element = x;
    });
}