본문 바로가기
코-딩/Javascript

Javascript - DOMParser, fetch

by ㅋㅂㅋ 2022. 3. 29.

가령 다운로드 할 파일의 내용을 변경해서 진행하고 싶을 때,

fetch와 DOMParser를 이용하면 된다.

 

let config = { headers: { 'Accept': 'application/json' } };

fetch( url, config )

.then(result => result.text()) //blob, text, json 등등등...

.then( function( res ) {

    console.log(res); //text로 변환된 파일 내용을 볼 수 있다.

});

 

html을 res로 받을 경우, text 상태에서 내용을 수정하기에 불편함이 있다.

다시 text > html로 변환을 시켜주기 위해 DOMParser를 사용한다.

 

let parser = new DOMParser();

let html = parser.parseFromString( res, "text/html" ); //xml 등등..

console.log(html); // #document로 시작하는 html을 볼 수 있다.

'코-딩 > Javascript' 카테고리의 다른 글

Javascript - blob & UTF-8  (0) 2022.04.14
JavaScript - image src  (0) 2022.03.31
getElementsByTagName() / querySelectorAll()  (0) 2022.01.19
Array.prototype.splice()  (0) 2022.01.12
Array.prototype.find()  (0) 2022.01.12