Search code examples
javascriptdomparserdocumentfragment

How to only append a certain part of a DOMParser result to a DocumentFragment element


I'm trying to append the html result of a DOMParser to a DocumentFragment which I then append to the body (after some load event).

Appending the whole DOMParser result works, however appending only the body part of the result fails.

response.text().then(function(text) {

  var content = new DOMParser().parseFromString(text, "text/html");
  var bodyPart = content.getElementsByTagName("body")[0].innerHTML;
  var fragmentElement = document.createDocumentFragment();
  var tempElement = fragmentElement.appendChild(bodyPart.documentElement);

  console.log(tempElement)

})

What am I doing wrong? Thx!


Solution

  • Don't call innerHTML, return as a node.

    response.text().then(function(text) {
    
          var content = new DOMParser().parseFromString(text, "text/html"),
              bodyPart = content.body,
              fragmentElement = document.createDocumentFragment(),
              tempElement = fragmentElement.appendChild(bodyPart);
    
          console.log(tempElement)
    
        })