我有一个表示元素的HTML字符串:“<li>text</li>”。我想将它附加到DOM中的一个元素(在我的例子中是一个ul)。如何使用Prototype或DOM方法做到这一点?
(我知道我可以在jQuery中轻松做到这一点,但不幸的是,我们没有使用jQuery。)
我有一个表示元素的HTML字符串:“<li>text</li>”。我想将它附加到DOM中的一个元素(在我的例子中是一个ul)。如何使用Prototype或DOM方法做到这一点?
(我知道我可以在jQuery中轻松做到这一点,但不幸的是,我们没有使用jQuery。)
当前回答
我添加了一个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>");
其他回答
为什么不使用原生js?
var s="<span class='text-muted' style='font-size:.75em; position:absolute; bottom:3px; left:30px'>From <strong>Dan's Tools</strong></span>"
var e=document.createElement('div')
var r=document.createRange();
r.selectNodeContents(e)
var f=r.createContextualFragment(s);
e.appendChild(f);
e = e.firstElementChild;
注意:大多数当前浏览器都支持HTML<template>元素,这提供了一种更可靠的方法来从字符串中创建元素。有关详细信息,请参阅下面Mark Amery的回答。
对于较旧的浏览器和node/jsdom:(在编写时还不支持<template>元素),请使用以下方法。这与库用来从HTML字符串中获取DOM元素的方法相同(IE需要额外的工作来解决innerHTML实现中的错误):
function createElementFromHTML(htmlString) {
var div = document.createElement('div');
div.innerHTML = htmlString.trim();
// Change this to div.childNodes to support multiple top-level nodes.
return div.firstChild;
}
注意,与HTML模板不同,这对于某些不能合法成为<div>的子元素的元素(如<td>s)不起作用。
如果您已经在使用一个库,我建议您坚持使用库批准的方法,从HTML字符串创建元素:
原型在其update()方法中内置了此功能。jQuery在其jQuery(html)和jQuery.parseHTML方法中实现了它。
var msg=“测试”jQuery.parseHTML(消息)
最新JS示例:
<template id="woof-sd-feature-box">
<div class="woof-sd-feature-box" data-key="__KEY__" data-title="__TITLE__" data-data="__OPTIONS__">
<h4>__TITLE__</h4>
<div class="woof-sd-form-item-anchor">
<img src="img/move.png" alt="">
</div>
</div>
</template>
<script>
create(example_object) {
let html = document.getElementById('woof-sd-feature-box').innerHTML;
html = html.replaceAll('__KEY__', example_object.dataset.key);
html = html.replaceAll('__TITLE__', example_object.dataset.title);
html = html.replaceAll('__OPTIONS__', example_object.dataset.data);
//convertion HTML to DOM element and prepending it into another element
const dom = (new DOMParser()).parseFromString(html, "text/html");
this.container.prepend(dom.querySelector('.woof-sd-feature-box'));
}
</script>
参观https://www.codegrepper.com/code-examples/javascript/convert+a+字符串+to+html+元素+in+js
const stringToHtml = function (str) {
var parser = new DOMParser();
var doc = parser.parseFromString(str, 'text/html');
return doc.body;
}