- 2 Ways To Add HTML Code In Javascript (A Quick Guide)
- TLDR – QUICK SLIDES
- TABLE OF CONTENTS
- WAYS TO ADD HTML CODE
- METHOD 1) DIRECTLY CHANGE HTML CODE
- METHOD 2) CREATE & APPEND HTML ELEMENTS
- MORE HTML SELECTION & INSERTION
- GET HTML ELEMENTS IN JAVASCRIPT
- SET HTML/CSS PROPERTIES
- TAKE EXTRA NOTE OF THE LOADING ORDER!
- DOWNLOAD & NOTES
- SUPPORT
- EXAMPLE CODE DOWNLOAD
- EXTRA BITS & LINKS
- DIRECT HTML MANIPULATION VS CREATING OBJECTS
- RECOMMENDED READS
- TUTORIAL VIDEO
- INFOGRAPHIC CHEAT SHEET
- THE END
- Leave a Comment Cancel Reply
- Search
- Breakthrough Javascript
- Socials
- About Me
- How to append HTML using JavaScript?
- Using innerHTML attribute
- JavaScript code:
- Using AdjacentHTML method
- Conclusion
- About the author
- Shehroz Azam
- Add HTML to Div Using JavaScript
- Use the createElement() Method to Add div in HTML
- Use the insertAdjacentHTML() Method to Add div Element
- Related Article - JavaScript Div
2 Ways To Add HTML Code In Javascript (A Quick Guide)
Welcome to a short beginner’s tutorial on how to add HTML code in Javascript. So you have finally gotten to the point of working with both HTML and Javascript, but the challenge is that you now have to add some HTML to an existing page.
Adding HTML code using Javascript is actually a simple “get target container and insert HTML” process:
- By directly changing or appending to the inner HTML.
- var target = document.getElementById(«ID»);
- target.innerHTML + ;
- By creating and inserting a new element.
- var newElement = document.createElement(«p»);
- newElement.innerHTML = «CONTENTS»;
- document.getElementById(«ID»).appendChild(newElement);
Yep. As simple as this select-insert mechanism may seem like, there are actually quite a few ways to select and insert elements. So let us walk through some actual examples in this tutorial – Read on!
TLDR – QUICK SLIDES
TABLE OF CONTENTS
WAYS TO ADD HTML CODE
All right, let us now move into the actual examples themselves – How we can work with Javascript to add HTML code and elements.
METHOD 1) DIRECTLY CHANGE HTML CODE
- (A) First, we give the HTML element a unique id .
- (B) Then select it with var ELEMENT = document.getElementById(ID) in Javascript.
- (C & D) Finally, take note that innerHTML can be used in two directions.
- var CONTENTS = ELEMENT.innerHTML to get the current contents.
- ELEMENT.innerHTML = «FOO!» to replace the contents.
- ELEMENT.innerHTML += «FOO!» to append to the existing contents.
METHOD 2) CREATE & APPEND HTML ELEMENTS
- (A & B) As usual, give the HTML element an id . Then use var PARENT = document.getElementById(«ID») to get it.
- (C) But instead of directly replacing the innerHTML , we create a new HTML element instead.
- We use var ELEMENT = document.createElement(«TAG») to create a new HTML tag.
- Then change the contents using ELEMENT.innerHTML = «FOO» … Which you already know.
- Finally, append the new element to the parent – PARENT.appendChild(ELEMENT) .
MORE HTML SELECTION & INSERTION
So far so good? Here are a few more examples of the various ways to select and insert HTML elements.
GET HTML ELEMENTS IN JAVASCRIPT
DemoD not John Wick.
// (B) GET BY ID var demoA = document.getElementById("demoA"); console.log(demoA); // ] // (D) GET BY CSS CLASS var demoC = document.getElementsByClassName("demoC"); console.log(demoC); // html collection - [demoD] // (F) GET BY QUERY SELECTOR var demoE = document.querySelector("#demoE strong"); console.log(demoE); // not // (G) GET BY QUERY SELECTOR (MULTIPLE SELECTORS) var demoF = document.querySelectorAll("span.demoC, p#demoE"); console.log(demoF); // node list - [ Getting elements by the id is not the only way in Javascript. There are plenty more that you should take note of.
SET HTML/CSS PROPERTIES
window.addEventListener("load", () => < // (A) GET HTML LIST var ul = document.getElementById("thelist"); // (B) DATA var data = ["Foo", "Bar", "Hello", "World", "John", "Doe"]; // (C) ADD LIST ITEMS for (let idx in data) < let li = document.createElement("li"); li.innerHTML = data[idx]; li.id = "item-" + idx; // set id li.style.color = "red"; // set style li.classList.add("dummy"); // add css class ul.appendChild(li); >>);
Remember the “create and append HTML element” example? Yes, we can also set the HTML/CSS properties in Javascript too.
TAKE EXTRA NOTE OF THE LOADING ORDER!
Lastly, this is a common pitfall among beginners – Not taking note of the order in which things are being loaded. Notice how demo is NULL in this example? Isn’t already defined!? Nope, Javascript is not broken. What happened is that HTML files load in a top-to-bottom, left-to-right manner.
The is loaded first, and ran before is even rendered – This is how getElementById("demo") ends up as a NULL . To solve this problem, we can use window.addEventListener("load") (as in the previous example) to wait for the window to be fully loaded before proceeding with the scripts.
DOWNLOAD & NOTES
Here is the download link to the example code, so you don’t have to copy-paste everything.
SUPPORT
600+ free tutorials & projects on Code Boxx and still growing. I insist on not turning Code Boxx into a "paid scripts and courses" business, so every little bit of support helps.
EXAMPLE CODE DOWNLOAD
Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
EXTRA BITS & LINKS
That’s all for this guide, and here is a small section on some extras and links that may be useful to you.
DIRECT HTML MANIPULATION VS CREATING OBJECTS
- innerHTML works better when you are dealing with changing the text contents inside a single element.
- createElement() makes more sense when you are dealing with lists and tables.
So yep – It is up to you to decide which is more comfortable.
RECOMMENDED READS
TUTORIAL VIDEO
INFOGRAPHIC CHEAT SHEET

THE END
Thank you for reading, and we have come to the end of this guide. I hope that it has helped you with your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!
Leave a Comment Cancel Reply
Search
Breakthrough Javascript

Take pictures with the webcam, voice commands, video calls, GPS, NFC. Yes, all possible with Javascript - Check out Breakthrough Javascript!
Socials
About Me

W.S. Toh is a senior web developer and SEO practitioner with over 20 years of experience. Graduated from the University of London. When not secretly being an evil tech ninja, he enjoys photography and working on DIY projects.
Code Boxx participates in the eBay Partner Network, an affiliate program designed for sites to earn commission fees by linking to ebay.com. We also participate in affiliate programs with Bluehost, ShareASale, Clickbank, and other sites. We are compensated for referring traffic.
How to append HTML using JavaScript?

Writing HTML code is easy, but when it comes to dynamic changes over the pages like appending HTML, you need to use unusual strategies. JavaScript is a powerful language to get such kinds of jobs done. You can easily use JavaScript to put the HTML code inside the template. We will discuss this in this write-up.
Through JavaScript, there are two ways to attach HTML code to a div tag.
- Using innerHTML property
- Inserting adjacent HTML using the insertAdjacentHTML() function
Using innerHTML attribute
To use the innerHTML property to attach code to an element (div), first pick the element (div) where you wish to append the code. Then, using the += operator on innerHTML, add the code wrapped as strings.
Here’s the syntax of the attribute.
Let’s take an example of this. First, we are going to be referring to the HTML element by using the property :
Therefore, let’s create a div> and put a h1> tag and a button> inside it.
< h1 >This is a LinuxHint Tutorial
As you can see, we have given an id of “test” to the div tag and placed the text that says “Append Paragraph” inside the button. With these, we have the following result on the screen

JavaScript code:
We have a button linked to a function named “buttonPressed()” in the script. But, we have not defined this function, and this button does not do anything. So, let’s create this function in the script that would add a paragraph in this div and count how many times we have added this paragraph. Take a look at the following code.
document. getElementById ( "test" ) . innerHTML +=
"
Yoo have append this paragraph " + i + " times" ;
Note: We have created a counter variable “i”. This will be used to keep a check on how many times have we append this paragraph inside the div tag.
Now, if we run the code and press the button we get:
Note: This technique essentially removes all of the div’s content and replaces it with new stuff. Any listeners linked to the child nodes of that div will be lost as a result. That is why we always concatenate it.
Using AdjacentHTML method
The insertAdjacentHTML() function can also be used to attach HTML code to a div. This method is comes in handy when it comes to appending HTML at some specific place. So it takes two parameters in this method:
- The location (in the document) where the code should be inserted (‘afterbegin’, ‘beforebegin’, ‘afterend’, ‘beforeend’).
- afterbegin – right after the HTML element mentioned but inside the tag.
- beforebegin – before the HTML element mentioned
- afterend – after the closing tag of the HTML element
- beforeend – inside the HTML element but before the closing tag
This is the general syntax of the method
HTMLelement.insertAdjacentHTML(‘LOCATION‘, ‘HTML CODE’);
Let’s use the previous example. The same HTML code. However, this time the script would be slight different as:
Note: Since we are using the previous example, the HTML code is exactly the same.
JavaScript Code:
i = 1 ;
function buttonPressed ( ) {
document. getElementById ( "test" ) . insertAdjacentHTML ( "beforebegin" ,
"
Appended " + i + " times Before Div
" ) ;
i ++;
}
Note: We are using the “beforebegin” property to append the tag before the start of the div.
That’s it, you have learned how can we append some HTML code through JavaScript.
Conclusion
There are two methods that you can use to append the HTML code into a webpage. The first method is by using innerHTML while the second method is by using the AdjacentHTML method. In this article, we have taken examples of both the innerHTML and AdjacentHTML methods to append the HTML code into a webpage.
About the author
Shehroz Azam
A Javascript Developer & Linux enthusiast with 4 years of industrial experience and proven know-how to combine creative and usability viewpoints resulting in world-class web applications. I have experience working with Vue, React & Node.js & currently working on article writing and video creation.
Add HTML to Div Using JavaScript

- Use the createElement() Method to Add div in HTML
- Use the insertAdjacentHTML() Method to Add div Element
To create a div element from JavaScript, you must manipulate the DOM. The most commonly used and preferred way depends on the createElement() method to create a div element.
We can also declare the necessary other elements inside the created div element. A less practiced method is the insertAdjacentHTML() , which is often not supported by Firefox and Safari.
In the following examples, we will see the use of both methods. The instances will create a div element under the main element having a specific id .
Use the createElement() Method to Add div in HTML
Here, we will first create a button element to trigger a function that will create a new element. We will also set the main element and an id=content for our new div elements to be added to this segment.
In our JavaScript lines, we will create an instance for the div element that will initiate the createElement('div') to set a value to the instance. In the innerHTML , we will also define a command that will ensure us that our div is created on function call.
html> head> meta charset="utf-8"> meta name="viewport" content="width=device-width"> title>testtitle> head> body> button onclick="add()">Make divbutton> main id="content">main> body> html>
function add() const div = document.createElement('div'); div.innerHTML = "new div"; document.getElementById('content').appendChild(div); >

With each click on the button, a new div element with the content new div is created. To be closely noticed is that the div element maintains the hierarchy of parent and child elements.
As the new div element is a child element of the main element, thus the appenChild() method is functioning.
Use the insertAdjacentHTML() Method to Add div Element
The insertAdjacentHTML() refers to a specific position and the right format for adding the child div element. In this case, we have this afterbegin parameter that creates a div right after the start, aka as a first child.
This loop will continue until it meets any condition to break.
html> head> meta charset="utf-8"> meta name="viewport" content="width=device-width"> title>testtitle> head> body> button onclick="add()">Make divbutton> main id="content">main> body> html>
function add() document.querySelector('#content').insertAdjacentHTML( 'afterbegin', ` ` ) >

As it can be seen, right after the afterbegin parameter, we have created the div element explicitly. Each button press creates a new div element relative to the previous div element.
This method is similar and defined to be executed properly, but some major browsers do not have modifications to deal with it.
Era is an observer who loves cracking the ambiguos barriers. An AI enthusiast to help others with the drive and develop a stronger community.
Related Article - JavaScript Div