How to insert a "node node string" into a page without the help of a container

existing variable str

var str = "<img src="xxx.jpg"/>"

I want to insert str directly into body

  • but I only know one method at present

    var domContainer =  document.createElement("div");
    domContainer.innerHTML = str;
    document.body.appendChild(domContainer)
    
  • when you do this, there will be a layer of div outside the img tag, although it does not affect the requirement implementation , but I wonder if the structure of the node string can be directly inserted into the page without the help of the container .
Apr.03,2021

document.body.innerHTML=' '


 document.body.innerHTML += str

object to the upstairs answer. Modify document.body directly. I'm afraid it's not the answer that the landlord wants. The + = operation needs to re-render all nodes, so the performance is not good.

you can generate DOM nodes and then remove them from the container, such as this:

 function appendDiv() {
      
        var text = '<div>456</div><div>789</div>';
        var divContainer = document.createElement('div');
        var fragment = document.createDocumentFragment();

        divContainer.innerHTML = text;

        while(divContainer.childNodes.length) {
            fragment.appendChild(divContainer.childNodes[0]);
        }


        document.body.appendChild(fragment);
    }  
Menu