Stephanie Parker
Stephanie Parker

Reputation: 401

Appending a template string

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

Answers (1)

Andreas
Andreas

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
    A DOMString representing the position relative to the element;
    must be one of the following strings:
        - 'beforebegin': Before the element itself.
        - 'afterbegin': Just inside the element, before its first child.
        - 'beforeend': Just inside the element, after its last child.
        - 'afterend': After the element 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

Related Questions