How to insert a large block of HTML in JavaScript?

html, javascript

Solution

`Template literals` may solve your issue as it will allow writing multi-line strings and string interpolation features. You can use variables or expression inside string (as given below). It's easy to insert bulk html in a reader friendly way.

I have modified the example given in question and please see it below. I am not sure how much browser compatible `Template literals` are. Please read about Template literals here.

var a = 1, b = 2;
var div = document.createElement('div');
div.setAttribute('class', 'post block bc2');
div.innerHTML = `
    <div class="parent">
        <div class="child">${a}</div>
        <div class="child">+</div>
        <div class="child">${b}</div>
        <div class="child">=</div>
        <div class="child">${a + b}</div>
    </div>
`;
document.getElementById('posts').appendChild(div);
.parent {
  background-color: blue;
  display: flex;
  justify-content: center;
}
.post div {
  color: white;
  font-size: 2.5em;
  padding: 20px;
}
<div id="posts"></div>

Problem

If I have a block of HTML with many tags, how do insert it in JavaScript? ``` var div = document.createElement('div'); div.setAttribute('class', 'post block bc2'); div.innerHTML = 'HERE TOO MUCH HTML that is much more than one line of code'; document.getElementById('posts').appendChild(div); ``` How do I do it right?

Original source

Related problems