Можно ли добавить строку шаблона в div? Я пытаюсь оптимизировать свой код, и в настоящее время мой код должен создать элемент, добавить классы, добавить текстовый узел, а затем добавить все вместе. Мне было интересно, можно ли просто создать строку шаблона, а затем добавить ее, чтобы быть более эффективным? Я не хочу стирать HTML-код текущего div с помощью innerHTML.
socket.on('coinFlip', (result) => {
const messages = document.querySelector('#messages');
const output = `<li class = "message broadcast">${result.result}</li>`;
messages.appendChild(output);
});
Текущий код, который работает:
socket.on('coinFlip', (result) => {
// Grab dialog box
const messages = document.querySelector('#messages');
// Render messages
const li = document.createElement('li');
li.className = "message broadcast";
const text = document.createTextNode(`${result.result}`);
li.appendChild(text);
messages.appendChild(li);
});



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Использовать Element.insertAdjacentHTML(position, text)
The
insertAdjacentHTML()method of the Element interface parses the specified text as HTML or XML and inserts the resulting nodes into the DOM tree at a specified position. It does not reparse the element it is being used on, and thus it does not corrupt the existing elements inside that element. This avoids the extra step of serialization, making it much faster than direct innerHTML manipulation.Parameters
position
ADOMStringrepresenting the position relative to theelement;
must be one of the following strings:
-'beforebegin': Before theelementitself.
-'afterbegin': Just inside theelement, before its first child.
-'beforeend': Just inside theelement, after its last child.
-'afterend': After theelementitself.
text
The string to be parsed as HTML or XML and inserted into the tree.
socket.on('coinFlip', (result) => {
const messages = document.querySelector('#messages');
const output = `<li class = "message broadcast">${result.result}</li>`;
messages.insertAdjacentHTML("beforeend", output);
});