How to append an html element from a string?

Hi,

I have a code like this, first my fixed html which is the container:

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

then the javascript that generates its contents:

 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. 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.

>Solution :

You can use insertAdjacentHTML:

messages.insertAdjacentHTML('beforeend', post)

Leave a Reply