从标记字符串创建节点

Create node from markup string

本文关键字:创建 节点 字符串      更新时间:2023-09-26

有没有一种方法可以在JavaScript中将标记字符串转换为节点对象?事实上,我正在寻找的替代品:

document.getElementById("divOne").innerHTML += "<table><tbody><tr><td><input type='text' value='0' /></td></tr></tbody></table>"

类似的东西

document.getElementById("divOne").appendChild(document.createNodeFromString("<table><tbody><tr><td><input type='text' value='0' /></td></tr></tbody></table>"))

使用createNodeFromString,而不是创建表元素,然后附加其子元素,然后添加它们各自的属性和值!

目前还没有跨浏览器的功能。可以使用以下方法来实现所需的效果(基于此答案,使用DocumentFragment来优化性能):

function appendStringAsNodes(element, html) {
    var frag = document.createDocumentFragment(),
        tmp = document.createElement('body'), child;
    tmp.innerHTML = html;
    // Append elements in a loop to a DocumentFragment, so that the browser does
    // not re-render the document for each node
    while (child = tmp.firstChild) {
        frag.appendChild(child);
    }
    element.appendChild(frag); // Now, append all elements at once
    frag = tmp = null;
}

用法(缩进以便于阅读):

appendStringAsNodes(
    document.getElementById("divOne"),
   "<table><tbody><tr><td><input type='text' value='0' /></td></tr></tbody></table>"
);

是的,你可以做到。

var myNewTable = document.createElement("table");
myNewTable.innerHTML = "<tbody><tr><td><input type='text' value='0' /></td></tr></tbody>"
document.getElementById("divOne").appendChild(myNewTable);

关于这个主题的一些新闻:

现代方法是使用<template>标记,例如在主体关闭之前放置(浏览器将忽略它)。

它是客户端模板的标准化,不需要使用.inerHTML,这可能会导致安全问题(XSS)

示例:

<template id='tplArticle'>
  <article class='newsItem'>
    <h1 class='title'></h1>
    <p class='paragraph'>
  </article>
</template>

每当你需要它时,你只需抓取它的内容并克隆(!!)它即可重用:

// .content will grab the content of the template, not the <template> tag
// this will return a document fragment
const $articleFragment = document.querySelector('#tplArticle').content;
// clone it, otherwise you get the same reference and it won't be reusable (true makes a deep copy)
const $article = document.importNode($articleFragment, true);
// then e.g. append it to the body
document.body.appendChild($article);
function htmlMarkupToNode(html){
    let template = document.createElement("template");        
    template.innerHTML = html ;
    let node = template.content.cloneNode(true) ;        
    return node ;   
}
document.getElementById("divOne").appendChild(htmlMarkupToNode("<table><tbody><tr><td><input type='text' value='0' /></td></tr></tbody></table>"));