Sometimes, we want to insert a large block of HTML in JavaScript.
In this article, we’ll look at how to insert a large block of HTML in JavaScript.
How to insert a large block of HTML in JavaScript?
To insert a large block of HTML in JavaScript, we use template literals.
For instance, we write
const a = 1;
const b = 2;
const 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);
to create the div
with createElement
.
Then we set its class
attribute with setAttribute
.
Next we set its content by setting the innerHTML
property to the HTML we want to render.
We use template literals to interpolate values in the HTML.
And then we call appendChild
to append the div
as the last child of the element with ID posts
.
Conclusion
To insert a large block of HTML in JavaScript, we use template literals.