Go to homepage

Projects /

An overview of the insertAdjacentHTML method in Javascript

An article on using the insertAdjacentHTML method.

An overview of the insertAdjacentHTML method in Javascript
By CodyHouse
404 HTML, CSS, JS components. Download →

In this article, we will explain what the insertAdjacentHTML method does, how to use it, and how it differs from other similar JavaScript methods. We will provide some real-life examples of where the method could be used and the possible errors associated with it.

What it does and how to use it #

The insertAdjacentHTML method is used to insert text as HTML in a specific DOM position.

var element = document.getElementsByClassName('my-class'),
  htmlString = '<p class="color-primary">Some text here</p>';

if(element.length > 0) {
  element[0].insertAdjacentHTML('beforebegin', htmlString);

In the above example, htmlString (the second argument of the method) is the text that should be parsed as HTML; I have used a single paragraph element, but you can create more complex strings with multiple elements, for example:

var htmlString = '<ul class="list"><li class="list__item">Item 1</li><li class="list__item">Item 2</li></ul>';

The first parameter of the method (in the example above 'beforebegin') specifies the position where the parsed text should be inserted. 'beforebegin' is used to insert content before an element; in our example, we are inserting a paragraph element (p.color-primary) right before element[0].

There are four possible values for the position parameter:

  • beforebegin: insert before the element;
  • afterend: insert after the element;
  • afterbegin: insert inside the element, before its first child;
  • beforeend: insert inside the element, after its last child.

Real-life cases #

Let's see this method in action in some real-life examples.

Read-more component #

Take a look at this Read more component.

It is used to hide part of a content element, providing a button to toggle the visibility of the remaining part.
For accessibility reasons, you should not hide the content by default: if JavaScript is enabled, you can hide the extra content, and create a button to control its visibility.

In your HTML, you could have a <p> element with the entire content, and then wrap the 'extra' content in an inline element (e.g., span.js-read-more__content):

<p class="read-more js-read-more">
  Lorem ipsum dolor, sit amet consectetur adipisicing elit. Odio corporis facilis, debitis a qui eum dolor repudiandae harum, impedit, fugit cumque. Tenetur... 
  <span class="js-read-more__content">Facere et voluptas sint similique, sequi corporis consectetur id suscipit est placeat ut expedita temporibus quisquam at illo dolores, laudantium assumenda!

In JS, we can now create a button element, and insert it right before the span.js-read-more__content element:

var extraContent = document.getElementsByClassName('js-read-more__content');
if(extraContent.length > 0) {
  // create the string that should be inserted as HTML 
  var btnShow = '<button class="js-read-more__btn">Read more</button>';
  // insert the button using insertAdjacentHTML
  extraContent[0].insertAdjacentHTML('beforebegin', btnShow);
  // hide the extra content
  extraContent[0].style.display = 'none';

Infinite Scroll component #

Check out this Infinite Scroll component.

When the user reaches the bottom of the page, new content is added to the list. Let's assume you have your additional content stored in a database and you can retrieve it as an array of objects, with a structure similar to the following:

let data = [
  {src: 'img-src-1.jpg', description: 'image description 1'},
  {src: 'img-src-2.jpg', description: 'image description 2'},
  {src: 'img-src-3.jpg', description: 'image description 3'},
  {src: 'img-src-4.jpg', description: 'image description 4'},
  // ...

Once retrieved, you can loop through it and create your custom string of additional content:

var htmlString = '';
// loop through the array of content
for(var i = 0; i < data.length; i++) {
  // create a list item with an image for each one of the object in the array
  htmlString = htmlString + '<li class="item">\
      <img src="'+data[i].src+'" alt="'+data[i].decription+'">\

Then append this string to your main wrapper element (after its last child):

var contentWrapper = document.getElementsByClassName('js-infinite-scroll__content');
if(contentWrapper.length > 0) {
  // insert the new content inside the contentWrapper, after its last child
  contentWrapper[0].insertAdjacentHTML('beforeend', htmlString);

insertAdjacentHTML vs other JavaScript methods #

Let's review some other JavaScript methods that are similar to insertAdjacentHTML, and explore their differences.

insertAdjacentHTML vs insertAdjacentElement #

The insertAdjacentElement method is used to insert a node element (not a text string) in the DOM at a specified position:

var element = document.getElementsByClassName('my-class'),
  nodeToInsert = document.createElement('p');

nodeToInsert.innerText = 'This is the content of the paragraph';

if(element.length > 0) {
  element[0].insertAdjacentElement('beforebegin', nodeToInsert);

As you can see from this example, insertAdjacentElement also accepts the position as the first parameter (same four values as insertAdjacentHTML), but then expects a node element as the second parameter.

Remember this difference, as passing a node element (rather than a text string) is one of the most common causes of errors when using the insertAdjacentHTML method.

insertAdjacentHTML vs innerHTML #

The innerHTML property is used to set/replace the content of an element:

var element = document.getElementsByClassName('my-class'),
  htmlString = '<p class="color-primary">Some text here</p>';

if(element.length > 0) {
  element[0].innerHTML = htmlString;

The content of element[0] will now be a paragraph (p.color-primary); if element[0] previously had some content, it has now been removed and replaced by the paragraph.

insertAdjacentHTML, on the other hand, can be used to specify the position where the content should be placed (rather than replacing the entire content), both inside or outside (right before or after) an element.

Project duplicated

Project created

Globals imported

There was an error while trying to export your project. Please try again or contact us.