Returning HTML With fetch()

后端 未结 5 1868
暗喜
暗喜 2020-11-28 03:45

I\'m trying to fetch a file and return it\'s HTML. However it\'s not as simple as I\'d have imagined.

    fetch(\'/path/to/file\')
    .then(function (respon         


        
5条回答
  •  情话喂你
    2020-11-28 04:22

    You can download the html with fetch and then parse it with DomParser API.

    fetch('somePage.html')
        .then(function(response) {
            // When the page is loaded convert it to text
            return response.text()
        })
        .then(function(html) {
            // Initialize the DOM parser
            var parser = new DOMParser();
    
            // Parse the text
            var doc = parser.parseFromString(html, "text/html");
    
            // You can now even select part of that html as you would in the regular DOM 
            // Example:
            // var docArticle = doc.querySelector('article').innerHTML;
    
            console.log(doc);
        })
        .catch(function(err) {  
            console.log('Failed to fetch page: ', err);  
        });

提交回复
热议问题