我有一个表示元素的HTML字符串:“<li>text</li>”。我想将它附加到DOM中的一个元素(在我的例子中是一个ul)。如何使用Prototype或DOM方法做到这一点?
(我知道我可以在jQuery中轻松做到这一点,但不幸的是,我们没有使用jQuery。)
我有一个表示元素的HTML字符串:“<li>text</li>”。我想将它附加到DOM中的一个元素(在我的例子中是一个ul)。如何使用Prototype或DOM方法做到这一点?
(我知道我可以在jQuery中轻松做到这一点,但不幸的是,我们没有使用jQuery。)
当前回答
最新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>
其他回答
您可以使用以下函数将文本“HTML”转换为元素
函数htmlToElement(html){var element=document.createElement('div');element.innerHTML=html;返回(元素);}var html=“<li>text和html</li>”;var e=htmlToElement(html);
迟到了,但只是一个音符;
可以将一个简单的元素作为容器添加到目标元素中,并在使用后将其删除。
//测试铬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>
var jtag = $j.li({ child:'text' }); // Represents: <li>text</li>
var htmlContent = $('mylist').html();
$('mylist').html(htmlContent + jtag.html());
使用jnerator
答复
创建模板将模板的innerHTML设置为strim.trim()创建模板的子级数组返回子项、子项或
函数toElement(s=“”,c,t=document.createElement('template'),l='length'){t.innerHTML=s.trim();c=[…t.content.childNodes];返回c[l]>1?c: c[0]| |“”;}console.log(toElement());console.log(toElement(“”));console.log(toElement(“”));console.log(toElement('<td>With td</td>'));console.log(toElement('<tr><td>With t</td></tr>'));console.log(toElement('<tr><td>foo</td></tr><tr><td>bar</td></tr>'));console.log(toElement('<div><span><span>嵌套</span><span>填充</span></div>'));
这也会奏效:
$('<li>').text('hello').appendTo('#mylist');
它感觉更像是一种带有链式函数调用的jquery方式。