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>