javascriptprependtemplate-literals

Using Javascript Template Literals With The prepend() Method


I have a loop of button elements that are outputted with a while loop from data called from a MySQL database via PHP.

A user can add a button to this list and I want to add the new button and it's associated HTML using the prepend() method on the parent element, so it appears at the top of the list.

I know how to do this in various stages using createElement and adding class names and attribute names, but wondered if there is a simpler way of doing it using a template literal of the required HTML?

I've seen plenty of examples using parentElement.innerHTML(variableName), where variableName is the template literal, but these button elements illustrated below are inside a loop, and want I to prepend the newly created button to the parent .board-list element shown in the HTML.

When a new board name is submitted, a fetch() post request happens in the background to update the database, but I need to create a new element with JavaScript so this shows instantly to the user.

At the moment the template literal newButton is added to the HTML inside quote marks as a string of text, not as HTML DOM elements.

JavaScript

// added into the template literal below
const newBoardName = document.querySelector('.input-title').value;

const newButton = `
<button class="board-list-item full-width" name="board-name" type="submit">
    <span>${newBoardName}</span>
    <span class="add-icon flex">+</span>
</button>
`

document.querySelector(".board-list").prepend(newButton);

HTML

<div class="board-list">

// buttons outputted from the database appear here

</div>

<form>
    <input class="input-title">
    <button name="new-board-name">New Board Name</button>
<form>

Solution

  • The solution to this was using the insertAdjacentHTML method. The question/answer given in one of the comments helped me on this, but I don't think it is a duplicate question, and the question linked to has an overly complicated answer IMHO.

    // added into the template literal below
    const newBoardName = document.querySelector('.input-title').value
    
    const newButton = `
    <button class="board-list-item full-width" name="board-name" type="submit">
        <span>${newBoardName}</span>
        <span class="add-icon flex">+</span>
    </button>
    `
    
    // insert using 'afterbegin' to add as the first child element
    document.querySelector(".board-list").insertAdjacentHTML('afterbegin', newButton)