Reputation: 401
Is it possible to append a template string to a div? I'm trying to optimise my code and currently my code is having to create element, add classes, add a text node and then append all together. I was wondering if its possible to just create a template string and then append that, to be more efficient? I don't want to wipe out the current div's html with innerHTML.
socket.on('coinFlip', (result) => {
const messages = document.querySelector('#messages');
const output = `<li class="message broadcast">${result.result}</li>`;
messages.appendChild(output);
});
Current code that works is:
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);
});
Upvotes: 9
Views: 10890
Reputation: 21881
Use 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
ADOMString
representing the position relative to theelement
;
must be one of the following strings:
-'beforebegin'
: Before theelement
itself.
-'afterbegin'
: Just inside theelement
, before its first child.
-'beforeend'
: Just inside theelement
, after its last child.
-'afterend'
: After theelement
itself.
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);
});
Upvotes: 20