Create a DOM document from string, without JQuery

后端 未结 9 496
梦如初夏
梦如初夏 2020-12-05 14:12

We\'re looking for ways to create a DOM document in javascript from a string, but without using Jquery. Is there a way to do so? [I would assume so, since J

9条回答
  •  孤城傲影
    2020-12-05 14:21

    The DOM element has the property innerHTML that allows to change completely its contents. So you can create a container and fill it with a new HTML content.

    function createElementFromStr(htmlContent) {
      var wrapperElm = document.createElement("div");
      wrapperElm.innerHTML = htmlContent; // Ex: "

    HTML string

    " console.assert(wrapperElm.children.length == 1); //Only one child at first level. return wrapperElm.children[0]; }

    * I know it is an old question, but i hope to help someone else.

提交回复
热议问题