Search code examples
javascripthtmldomtemplate-literals

Using template strings to append HTML


Is there a way to append HTML using template literals in the DOM without overwriting what was currently posted?

I have a huge block of HTML that I need to post for a list that is being created, where a user is able to post their input.

Every time the task is submitted, it overwrites the current submission. I need it to append underneath.

This is the fiddle for demonstration purpose.

HTML:

<div class="main-content">
  <form class="new-items-create">
    <label>Name:</label>

    <input
      placeholder=" A Name"
      id="name"
    />

    <button class="subBtn">Submit</button>
  </form>
</div>

<span class="new-name"></span>

JavaScript:

form.addEventListener("submit", addItem);

function addItem(event) {
  event.preventDefault();

  let htmlStuff = `
         <div class="main">
        <div class="a name">
         <span>${name.value}</span>
        </div>
        <div>
        `;

  itemCreated.innerHTML = htmlStuff;
}


Solution

  • insertAdjacentHTML() adds htmlString in 4 positions see demo. Unlike .innerHTML it never rerenders and destroys the original HTML and references. The only thing .innerHTML does that insertAdjacentHTML() can't is to read HTML. Note: assignment by .innerHTML always destroys everything even when using += operator. See this post

    const sec = document.querySelector('section');
    
    sec.insertAdjacentHTML('beforebegin', `<div class='front-element'>Front of Element</div>`)
    
    sec.insertAdjacentHTML('afterbegin', `<div class='before-content'>Before Content</div>`)
    
    sec.insertAdjacentHTML('beforeend', `<div class='after-content'>After Content</div>`)
    
    sec.insertAdjacentHTML('afterend', `<div class='behind-element'>Behind Element</div>`)
    * {
      outline: 1px solid #000;
    }
    
    section {
      margin: 20px;
      font-size: 1.5rem;
      text-align: center;
    }
    
    div {
      outline-width: 3px;
      outline-style: dashed;
      height: 50px;
      font-size: 1rem;
      text-align: center;
    }
    
    .front-element {
      outline-color: gold;
    }
    
    .before-content {
      outline-color: blue;
    }
    
    .after-content {
      outline-color: green;
    }
    
    .behind-element {
      outline-color: red;
    }
    <section>CONTENT OF SECTION</section>