How do I append HTML from a document loaded with AJAX?

前端 未结 6 1472
闹比i
闹比i 2021-01-13 19:13

I am trying to append the contents of a .html file to the body of my main page. Basically, I am trying to make a reusable chunk of html that I can load into any page with a

6条回答
  •  一整个雨季
    2021-01-13 19:32

    Js haven't native method for this task, but you can use jquery method load

    ${element}.load('./template.html');
    

    Or, create element-container, and use innerHTML prop

    request.addEventListener("load", function(event_) {
        //This is the problem line of code
        //How do I get the contents of my response to act like an element? 
        var container = document.createElement("div");
        container.innerHTML = this.responseText;
        document.body.appendChild(container);
    }, false);
    

    UPD
    Convert string to DOM.

    function strToDom(str) {
        var tempEl = document.createElement('div');
        tempEl.innerHTML = str;
        return tempEl.children[0];
    }
    

    NOTE: string element should be one root element, that wraps others

    ...

    not


提交回复
热议问题