How to Add Markup Inside Elements With JavaScript

Learn how to add an element inside another element with JavaScript.

JavaScript has a property called innerHTML that makes adding markup inside existing elements straight forward.

Let’s say you have an article header with a headline, and you need to add an important message right below it, like a subtitle or a tagline.

HTML

<article>
  <header>
    <h1>Headline for your article</h1>
  </header>
</article>

JavaScript

Now let’s add some HTML markup for the tagline right after the h1 headline.

// Select h1 element inside the article element
const articleHeadline = document.querySelector('article header')

// Add content right after the h1 element
articleHeadline.innerHTML += '<p>Extra content right below the headline.</p>'

Pretty cool, huh?

What if you need to add content right above the h1 headline instead of below it?

No problem, you first assign the new content to your articleHeadline variable and then add the headline content afterward:

articleHeadline.innerHTML = '<p>Extra content right before the headline.</p>' + articleHeadline.innerHTML