我有一个表示元素的HTML字符串:“<li>text</li>”。我想将它附加到DOM中的一个元素(在我的例子中是一个ul)。如何使用Prototype或DOM方法做到这一点?

(我知道我可以在jQuery中轻松做到这一点,但不幸的是,我们没有使用jQuery。)


当前回答

我自己找了很多,找到了一个很好的解决方案。

const stringToHTML = (str) => {
    var parser = new DOMParser();
    var doc = parser.parseFromString(str, 'text/html');
    return doc.body;
};

要转换的字符串:

'<iframe src="https://player.vimeo.com/video/578680903?h=ea840f9223&amp;app_id=122963" width="640" height="360" frameborder="0" allow="autoplay; fullscreen; picture-in-picture" allowfullscreen title="Total Body Balance"></iframe>'

结果:

<body><iframe src="https://player.vimeo.com/video/578680903?h=ea840f9223&amp;app_id=122963" width="640" height="360" frameborder="0" allow="autoplay; fullscreen; picture-in-picture" allowfullscreen="" title="Total Body Balance"></iframe></body>

其他回答

解决方案-适用于自IE 4.0以来的所有浏览器

var htmlString = `<body><header class="text-1">Hello World</header><div id="table"><!--TABLE HERE--></div></body>`;
var tableString = `<table class="table"><thead><tr><th>th cell</th></tr></thead><tbody><tr><td>td cell</td></tr></tbody></table>`;


var doc = document.implementation.createHTMLDocument();
    doc.open();
    doc.write(htmlString);
    doc.getElementById('table').insertAdjacentHTML('beforeend', tableString);
    doc.close();

console.log(doc);

或者你可以使用DOMParser

var doc = (new DOMParser).parseFromString(htmlString, "text/html");
    doc.getElementById('table').insertAdjacentHTML('beforeend', tableString);

console.log(doc);

以下是如何使用PrototypeJS(正如OP 12年前最初要求的那样):

HTML格式:

<ul id="mylist"></ul>

JS:

$('mylist').insert('<li>text</li>');

注意,这不是jQuery!

对于某些html片段,如<td>test</td>、div.innerHTML、DOMParser.parseFromString和range.createContextualFragment(没有正确的上下文),此处其他答案中提到的解决方案不会创建<td>元素。

jQuery.parseHTML()正确处理它们(我将jQuery2的parseHTML函数提取为一个独立函数,可以在非jQuery代码库中使用)。

如果您只支持Edge 13+,那么只使用HTML5模板标记会更简单:

function parseHTML(html) {
    var t = document.createElement('template');
    t.innerHTML = html;
    return t.content;
}

var documentFragment = parseHTML('<td>Test</td>');

迟到了,但只是一个音符;

可以将一个简单的元素作为容器添加到目标元素中,并在使用后将其删除。

//测试铬23.0,萤火虫18.0,即7-8-9和歌剧12.11。

<div id="div"></div>

<script>
window.onload = function() {
    var foo, targetElement = document.getElementById('div')
    foo = document.createElement('foo')
    foo.innerHTML = '<a href="#" target="_self">Text of A 1.</a> '+
                    '<a href="#" onclick="return !!alert(this.innerHTML)">Text of <b>A 2</b>.</a> '+
                    '<hr size="1" />'
    // Append 'foo' element to target element
    targetElement.appendChild(foo)

    // Add event
    foo.firstChild.onclick = function() { return !!alert(this.target) }

    while (foo.firstChild) {
        // Also removes child nodes from 'foo'
        targetElement.insertBefore(foo.firstChild, foo)
    }
    // Remove 'foo' element from target element
    targetElement.removeChild(foo)
}
</script>

我添加了一个Document原型,它从字符串创建一个元素:

Document.prototype.createElementFromString = function (str) {
   const element = new DOMParser().parseFromString(str, 'text/html');
   const child = element.documentElement.querySelector('body').firstChild;
   return child;
};

用法:

document.createElementFromString("<h1>Hello World!</h1>");