Search code examples
javascripthtmljsonxmlhttprequeststringify

Is there a way to JSON.stringify an HTML dom object? [JavaScript]


I am trying to load in a external html file and stringify the contents within the body but can't seem to do so without it producing undesired results. Is there even a way to do this?

var xhr = new XMLHttpRequest();

function loadFile(){
    xhr.open("GET", 'index.html');
    xhr.responseType = "document";
    xhr.send();
}

xhr.onload = function(data) {
    myData = data;
    myString = JSON.stringify(myData.srcElement.responseXML.body.children);
        console.log(myString)
       //logs: {"0":{},"length":1}

    }

loadFile();

But what I need it to load is the actual div contents, ex:

//log: '<div id ='mydiv'>...</div>

What am I doing wrong?


Solution

  • I was able to figure this out by changing the response type to 'DOMString':

    function buildAd(file){
        xhr.open("GET", file);
        xhr.responseType = "DOMString";
        xhr.send();
    }