3

I would like to add some html to append to a div in a function like this

const chatContainer = document.getElementById('chat');
    chatContainer.appendChild(`
        <div class="message-data align-center">
            <span class="message-data-name" >User joined</span>
        </div>
    `)

but the previous exemple do not work.

4 Answers 4

3
var innerdiv = `<div class="message-data align-center">
            <span class="message-data-name" >User joined</span>
        </div>`;
document.getElementById('chat').innerHTML += innerdiv;

<div id="chat"> </div>
Sign up to request clarification or add additional context in comments.

Comments

2

.appendChild expects the argument it is called with to be a DOM node. So you need to parse the string into the DOM node prior to appending it.

const parser = new DOMParser();
const chatContainer = document.getElementById('chat');
chatContainer.appendChild(parser.parseFromString(`
    <div class="message-data align-center">
        <span class="message-data-name" >User joined</span>
    </div>
`, 'text/xml').firstChild)
<div id='chat'>

Comments

1

Use insertAdjacentHTML instead:

chatContainer.insertAdjacentHTML('beforeend', `
        <div class="message-data align-center">
            <span class="message-data-name" >User joined</span>
        </div>
    `);
<div id="chatContainer"></div>

You can also use

chatContainer.innerHTML += `< ...html string >`

, but that will corrupt any existing event listeners attached to any of chatContainer's children.

1 Comment

.innerHTML += ...: ...and will force the browser to unnecessarily parse the complete content of chatContainer instead of only the added markup.
0

Why not use a function to append a new message to your chat?

function addMessage(chat, text){
    let msg = document.createElement("div");
    msg.classList.add("message-data", "align-center");
    // it's shorter to just insert the span as HTML-text directly here
    msg.innerHTML = `<span class="message-data-name">${text}</span>`
    return chat.appendChild(msg);
}

Or maybe use a chat-class with other methods as well?

var Chat = (function(){
  function Chat(selector){
    this.element = document.querySelector(selector);
  }
  Chat.prototype = {
    constructor: Chat,
    addMessage: function(text){
      let msg = document.createElement("div");
      msg.classList.add("message-data", "align-center");
      msg.innerHTML = `<span class="message-data-name">${text}</span>`;
      return this.element.appendChild(msg);
    }
  }
  return Chat;
}());

const chat = new Chat("#chat");
chat.addMessage("User joined");
chat.addMessage("FooBar");
#chat {
  background: #eee;
  border: 2px solid #000;
}

.align-center {
  text-align: center;
}

.message-data {
  border: 1px solid #000;
  padding: 5px;
}
<div id="chat"></div>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.