Skip to content
Advertisement

Insert HTML code to div onClick but does not replace existing code

I would like to insert HTML code to make a “list”. I’ve seen examples of innerHTML but that just replaces the existing code. How can I add more code without replacing the current code?

var addTo = document.querySelector(".activePage")[0];
var addHTML = '
<div id="item1">
  <h1>This is a heading</h1>
  <p>This is a paragraph</p>
</div>'

addTo.innerHTML(addHTML)'
<nav class="activePage"><nav>

Advertisement

Answer

Use insertAdjacentHtml. Docs – https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML.

var addTo = document.querySelector(".activePage");

var addHTML = '<div id="item1"><h1>This is a heading</h1><p>This is a paragraph</p></div>

addTo.insertAdjacentHtml(addHTML, 'beforeEnd')

‘beforeEnd’ means it will add right before the end of the element(inside the element).

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement