Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
How to make Live Coding Editor using HTML CSS and JavaScript ?
Next article icon

How to append HTML code to a div using JavaScript ?

Last Updated : 15 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Updating content on a webpage without reloading the entire page makes for a faster and smoother user experience. JavaScript allows you to do this by adding new HTML to elements like divs dynamically.

There are four simple ways to add HTML to a div using JavaScript:

  • Using the innerHTML Attribute
  • Using the insertAdjacentHTML() Method
  • Using the appendChild() Method
  • Using the append() Method

Let’s go through each method and see how they work.

1. Using the innerHTML Attribute

The innerHTML attribute is one of the most straightforward ways to append new HTML to a div. You simply access the innerHTML of the div and add the new HTML code to it using the += operator.

html
<html> <head>     <title>         How to Append HTML Code to         a Div using Javascript?     </title>      <style>         body {             text-align: center;             padding: 5%;         }          h1 {             color: green;         }     </style> </head>  <body>     <div id="add_to_me">         <h1>GeeksforGeeks</h1>         <p>             This is the text which has             already been typed into             the div         </p>     </div>      <button onclick="addCode()">         Add Stuff     </button>      <script>         function addCode() {             document.getElementById("add_to_me")                 .innerHTML +=                 `<h3>                     This is the text which has                     been inserted by JS                 </h3>`;         }     </script> </body> </html> 

Output:

In this code

  • They dynamically adds content to a <div> when a button is clicked.
  • Initially, the div contains a heading and a paragraph.
  • When the “Add Stuff” button is clicked, a new <h3> element is appended to the div using JavaScript’s innerHTML += method.

Note: This method basically destroys all the content of the div and recreates it. So, if you have any listeners attached to the child nodes of that div, they will be lost.

2. Using the insertAdjacentHTML() Method

The insertAdjacentHTML() method method allows you to insert HTML into a div at specific positions. You can specify where you want the new content relative to the existing content.

HTML
<html> <head>     <title>         How to Append HTML Code to         a Div using Javascript?     </title>      <style>         body {             text-align: center;             padding: 5%;         }          h1 {             color: green         }     </style> </head> <body>     <div id="add_to_me">         <h1>GeeksforGeeks</h1>          <p id="add_after_me">             This is the text which has             already been typed into             the div         </p>     </div>      <button onclick="addCode()">         Add Stuff     </button>      <script>         function addCode() {             document.getElementById("add_after_me")                 .insertAdjacentHTML("afterend",                     `<h3>                         This is the text which has                         been inserted by JS                     </h3>`);         }     </script> </body>  ]</html> 

Output

In this code

  • It adds a new <h3> element after the existing <p> element inside a div when the “Add Stuff” button is clicked.
  • It uses JavaScript’s insertAdjacentHTML(“afterend”, …) to insert the new content after the specified element (add_after_me).

3. Using the appendChild() Method

The appendChild() method allows you to append an actual HTML element to a div. This method works differently because you need to first create the new HTML element and then append it to the div.

HTML
<html>   <head>     <meta charset="UTF-8">     <meta name="viewport" content="width=device-width,                                     initial-scale=1.0">     <title>         Append HTML to a div in JavaScript     </title>     <style>         #conatiner{             text-align: center;         }     </style> </head> <body>     <div id="conatiner">         <h1 style="color: green">             GeeksforGeeks         </h1>         <h3>             Click the below button to append the             HTML to a Div.         </h3>         <button id="btn">Append HTML</button>     </div>     <script>         const btn = document.getElementById('btn');         function appendHTML(){             const ele = document.getElementById('conatiner');             const newDiv = document.createElement('div');             newDiv.innerHTML =               `                 <h2>                     Hey Geek,<br/>                     Welcome to GeeksforGeeks!!                 </h2>                 <h3>                     This is the HTML appended using the                      appendChild() method in JavaScript.                 </h3>             `;             ele.appendChild(newDiv);         }         btn.addEventListener('click', appendHTML);     </script> </body> </html> 

Output:

appendHTMLGIF

In this code

  • This HTML document adds new content to a <div> when a button is clicked.
  • It uses JavaScript to create a new <div>, adds HTML inside it, and appends it to the existing #conatiner div using appendChild().

NOTE: You should never insert the HTML code in this way if you are taking it as input from the user. It opens your website to cross-site scripting vulnerabilities.

4. Using the append() Method

The append() method is a more modern way to append content. Unlike appendChild(), which only allows you to append DOM elements, append() can append both DOM nodes and text or HTML strings. It also allows you to append multiple nodes at once.

HTML
<html> <head>     <meta charset="UTF-8">     <meta name="viewport" content="width=device-width, initial-scale=1.0">     <title>GeeksforGeeks - Appending HTML with append()</title>     <style>         body {             font-family: Arial, sans-serif;             background-color: #f4f4f9;             color: #333;             text-align: center;             margin: 0;             padding: 0;         }          #container {             margin-top: 50px;             padding: 20px;             background-color: #fff;             border: 2px solid #ddd;             border-radius: 8px;             box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);             width: 50%;             margin-left: auto;             margin-right: auto;         }          h1 {             color: #4CAF50;         }          button {             padding: 10px 20px;             background-color: #4CAF50;             color: white;             border: none;             border-radius: 5px;             cursor: pointer;             font-size: 16px;             margin-top: 20px;         }          button:hover {             background-color: #45a049;         }          p {             color: #555;         }     </style> </head>  <body>      <div id="container">         <h1>GeeksforGeeks</h1>         <p>Click below to add new content!</p>     </div>     <button onclick="addContent()">Add New Content</button>     <script>         function addContent() {             var container = document.getElementById('container');             var newParagraph = document.createElement('p');             newParagraph.textContent = 'New content added dynamically!';             container.append(newParagraph);         }     </script> </body> </html> 

Output

append-method-

append() Method

In this code

  • This HTML page uses JavaScript to dynamically add content to a div.
  • When the “Add New Content” button is clicked, a new paragraph is created and appended to the #container div.
  • The page is styled with a clean, centered layout and a button that changes color on hover.

JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples .

Conclusion

Dynamically adding HTML content to a webpage using JavaScript enhances interactivity and provides a seamless user experience. Whether you use methods like innerHTML, insertAdjacentHTML, appendChild(), or the more flexible append(), each method has its own advantages and best-use scenarios.



Next Article
How to make Live Coding Editor using HTML CSS and JavaScript ?

J

JacobAntony1
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • HTML-Attributes
  • JavaScript-Questions

Similar Reads

  • How To Build Notes App Using Html CSS JavaScript ?
    In this article, we are going learn how to make a Notes App using HTML, CSS, and JavaScript. This project will help you to improve your practical knowledge in HTML, CSS, and JavaScript. In this notes app, we can save the notes as titles and descriptions in the local storage so the notes will stay th
    4 min read
  • How to Append Header to a HTML Table in JavaScript ?
    JavaScript allows us to dynamically modify the structure of a table based on user interaction or other dynamic events. Here we will use JavaScript to dynamically create a Header row and then append it to the HTML table. ApproachIn this approach, we are using create elements along with DOM manipulati
    3 min read
  • How to Get the Content of an HTML Comment using JavaScript ?
    In this article, we will learn how to get the content of an HTML Comment Using Javascript. Comments are a best practice in programming and software development. In general, they can explain why a coding decision was made or what needs to be done to improve the code you're working on. HTML tags (incl
    3 min read
  • How to append data to <div> element using JavaScript ?
    To append the data to <div> element we have to use DOM(Document Object Model) manipulation techniques. The approach is to create a empty <div> with an id inside the HTML skeleton. Then that id will be used to fetch that <div> and then we will manipulate the inner text of that div.
    1 min read
  • How to make Live Coding Editor using HTML CSS and JavaScript ?
    In this article, we will implement a live coding editor using HTML, CSS, and JavaScript. This project will allow you to write and execute HTML, CSS, and JavaScript code in real-time, making it an excellent tool for learning and testing your code snippets. Final Output PrerequisiteHTMLCSSJavaScriptAp
    3 min read
  • How to add HTML elements dynamically using JavaScript ?
    We learn how to add HTML elements dynamically using JavaScript. A basic understanding of HTML, CSS, and JavaScript is required. Here we are going to use a button and by clicking this button, we can add an HTML element dynamically in this example. Below are the approaches used to add HTML elements dy
    2 min read
  • How to Change Text Inside all HTML Tags using JavaScript ?
    In this article, we will learn how to change the text content inside all HTML tags using JavaScript. This skill is valuable when you need to dynamically modify the text displayed on a web page. which can be useful for various scenarios like updating content, internationalization, or creating dynamic
    3 min read
  • How to add/update an attribute to an HTML element using JavaScript?
    To add/update an attribute to an HTML element using JavaScript, we have multiple approaches. In this article, we are going to learn how to add/update an attribute to an HTML element using JavaScript. Below are the approaches used to add/update an attribute to an HTML element using JavaScript: Table
    2 min read
  • How to Create an HTML Table from an Object Array Using JavaScript ?
    Tables are a fundamental part of web development, and displaying data in a structured manner is a common requirement. JavaScript provides a powerful way to dynamically generate HTML content, making it easy to create tables from object arrays. Table of Content Using innerHTML propertyUsing appendChil
    2 min read
  • How to Combine multiple elements and append the result into a div using JavaScript ?
    Combining multiple elements and appending elements to DOM is a crucial process, it would become a time-consuming process. If not handled properly so as a developer we should know how to update the DOM effectively. So following are the three ways to append HTML elements to DOM. The following methods
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences