我有一个表示元素的HTML字符串:“<li>text</li>”。我想将它附加到DOM中的一个元素(在我的例子中是一个ul)。如何使用Prototype或DOM方法做到这一点?
(我知道我可以在jQuery中轻松做到这一点,但不幸的是,我们没有使用jQuery。)
我有一个表示元素的HTML字符串:“<li>text</li>”。我想将它附加到DOM中的一个元素(在我的例子中是一个ul)。如何使用Prototype或DOM方法做到这一点?
(我知道我可以在jQuery中轻松做到这一点,但不幸的是,我们没有使用jQuery。)
当前回答
这也会奏效:
$('<li>').text('hello').appendTo('#mylist');
它感觉更像是一种带有链式函数调用的jquery方式。
其他回答
参观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;
}
这也会奏效:
$('<li>').text('hello').appendTo('#mylist');
它感觉更像是一种带有链式函数调用的jquery方式。
function domify (str) {
var el = document.createElement('div');
el.innerHTML = str;
var frag = document.createDocumentFragment();
return frag.appendChild(el.removeChild(el.firstChild));
}
var str = "<div class='foo'>foo</div>";
domify(str);
您可以使用以下函数将文本“HTML”转换为元素
函数htmlToElement(html){var element=document.createElement('div');element.innerHTML=html;返回(元素);}var html=“<li>text和html</li>”;var e=htmlToElement(html);
最新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>