How To

Learn How to JavaScript Append HTML to Body

In this JavaScript tutorial we learn about how we use JavaScript Append HTML to Body. There are two ways or JavaScript method...

Written by Bikash · 1 min read >

In this JavaScript tutorial we learn about how we use JavaScript Append HTML to Body. There are two ways or JavaScript method which we use to append HTML element to the HTML body.

  1. Using innerHTML attribute, innerHTML is the HTML DOM property.
  2. Using insertAdjacentHTML() DOM function.
 JavaScript Append HTML to Body

Using innerHTML DOM property

Introduction to innerHTML Attribute

InnerHTML attribute is the DOM (Document Object Model) property. It is used for setting the HTML content to the element.

Below is the example of how we use innerHTML on our code,

Syntax: HTMLElementObject.innerHTML = text

Append HTML to Body Using innerHTML

See the Pen
Append HTML to Body Using innerHTML
by Bikash Panda (@phpcodertech)
on CodePen.

Note: This method basically removes all the content from the div and recreate the new div with new content. So if you have any child node they will also remove.

Using insertAdjacentHTML() DOM function

Introduction to insertAdjacentHTML() DOM function

insertAdjacentHTML() DOM function is used for insert div content or any HTML content on the following mentioned position,

  • “afterbegin”
  • “afterend”
  • “beforebegin”
  • “beforeend”

Syntax: node.insertAdjacentHTML(position, text)

Append HTML to Body Using innerHTML

See the Pen Example of insertAdjacentHTML() DOM function by Bikash Panda (@phpcodertech) on CodePen.

https://static.codepen.io/assets/embed/ei.js

Here is a complete reference about how we append HTML element inside or any predefined position on the div element.

Conclusion

On the above tutorial we use 2 method to append HTML element using JavaScript DOM methods,

  • Using innerHTML
    Syntax: HTMLElementObject.innerHTML = text
  • Using insertAdjacentHTML
    Syntax: node.insertAdjacentHTML(position, text)

This is a complete solution where we check JavaScript append functionality with live example.

If you have facing issue please comment below.

Also Check:

Happy Coding..!

Was this article helpful?
YesNo
Written by Bikash
My name is Bikash Kr. Panda. I own and operate PHPCODER.TECH. I am a web Programmer by profession and working on more than 50 projects to date. Currently I am working on the web-based project and all the CMS and frameworks which are based on PHP. Profile

3 Replies to “Learn How to JavaScript Append HTML to Body”

Leave a Reply

Your email address will not be published. Required fields are marked *