Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can fetch() do responseType=document?

XHR's responseType='document' is awesome because it hands you back a DOM document that you can use querySelector, etc on:

var xhr = new XMLHttpRequest();
xhr.open('GET', '/', true);
xhr.responseType = 'document';
xhr.onload = function(e) {
  var document = e.target.response;
  var h2headings = document.querySelectorAll('h2');
  // ...
};

Is this possible with the fetch method?

like image 672
Paul Irish Avatar asked Mar 08 '23 10:03

Paul Irish


1 Answers

It's not natively supported in fetch as the API is a purely network-layer API with no dependencies on being in a web browser (see discussion), but it's not too hard to pull off:

fetch('/').then(res => res.text())
  .then(text => new DOMParser().parseFromString(text, 'text/html'))
  .then(document => {
    const h2headings = document.querySelectorAll('h2');
    // ...
  });
like image 126
Paul Irish Avatar answered Apr 01 '23 11:04

Paul Irish