简体   繁体   English

如何从字符串中附加一个 html 元素?

[英]How to append an html element from a string?

Hi,你好,

I have a code like this, first my fixed html which is the container:我有这样的代码,首先是我的固定 html,它是容器:

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

then the javascript that generates its contents:然后是生成其内容的 javascript:

 var post = `<div id="${userid}">${content}</div>`;
 var item = document.createElement('div');
 item.innerHTML = post;
 messages.appendChild(item);

the problem with this is that it wrapps each post in a div which I dont need.问题在于它将每个帖子包装在我不需要的 div 中。 This should be the output这应该是输出

<div id="messages">
 <div id="user45">some content</div>
 <div id="user46">more content</div>
</div>

how can I append the content of the string directly to the container without the wrapper?如何在没有包装器的情况下将字符串的内容直接附加到容器?

Thank you.谢谢你。

您可以使用insertAdjacentHTML

messages.insertAdjacentHTML('beforeend', post)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM