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:

  1. By directly changing or appending to the inner HTML.
    • var target = document.getElementById("ID");
    • target.innerHTML += "<p>CONTENTS</p>";
  2. 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!

ⓘ I have included a zip file with all the example source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

QUICK SLIDES

 

TABLE OF CONTENTS

Download & Notes Ways To Add HTML More Examples
Useful Bits & Links Tutorial Video The End

 

DOWNLOAD & NOTES

First, here is the download link to the example source code as promised.

 

EXAMPLE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

QUICK NOTES

If you spot a bug, please feel free to comment below. I try to answer questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

 

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

1-direct-code.html
<!-- (A) TARGET ELEMENT -->
<div id="elementA">Foo Bar!</div>
 
<script>
window.addEventListener("load", function(){
  // (B) GET ELEMENT
  var element = document.getElementById("elementA");
  console.log(element);
 
  // (C) THIS WILL REPLACE THE CONTENTS
  element.innerHTML = "John Doe";
 
  // (D) THIS WILL APPEND TO THE CONTENTS
  element.innerHTML += " is <strong>NOT</strong> John Wick.";
});
</script>

This first method will use the innerHTML property to directly manipulate the HTML.

  • First, we give the HTML element a unique id.
  • Then select it with var element = document.getElementById(ID) in Javascript.
  • Finally, take note that innerHTML can be used in two directions.
    • var contents = element.innerHTML will get the current contents of element.
    • element.innerHTML = "FOO!" it will replace the contents of element instead.

 

 

METHOD 2) CREATE & APPEND HTML ELEMENTS

2-create-element.html
<!-- (A) TARGET ELEMENT -->
<div id="elementA">John Doe</div>
 
<script>
window.addEventListener("load", function(){
  // (B) GET PARENT ELEMENT
  var parent = document.getElementById("elementA");
 
  // (C) CREATE ELEMENT + SET CONTENTS
  var newbie = document.createElement("strong");
  newbie.innerHTML = " SAYS ";
  parent.appendChild(newbie);
 
  // (D) CREATE NEW TEXT NODE
  newbie = document.createTextNode("uvuvwevwevwe onyetenyevwe ugwemubwem ossas");
  parent.appendChild(newbie);
});
</script>

This method is a little more “object-oriented”, creating new HTML elements in Javascript and appending them into the document.

  • Just like the previous example, we get the parent element using var parent = document.getElementById("ID") first.
  • But instead of directly replacing the HTML, we create a new element with var newbie = document.createElement("TAG").
  • Then, we replace the contents of the new element using newbie.innerHTML = "FOO"… Which you should already be an expert with.
  • Finally, we append the newly created element to the parent – parent.appendChild(newbie).
  • If you just want to append text to an element, then just create a text node instead – newbie = document.createTextNode("TEXT"). Then the same applies – Append it to the parent.

Yep. While this may seem to be a little bit more long-winded, this method will make sense when it comes to building lists and tables. More examples below.

 

TAKE EXTRA NOTE OF THE LOADING ORDER!

3-load-order.html
<script>
// (A) JAVASCRIPT IS LOADED FIRST
var element = document.getElementById("elementA");
console.log(element); // NULL
</script>
 
<!-- (B) ELEMENT IS LOADED ONLY AFTER THE JAVASCRIPT -->
<div id="elementA">Foo Bar!</div>

The above examples should be pretty straightforward, but one common pitfall among beginners is not taking note of the order in which things are being loaded.  Notice how element is NULL in this case? Isn’t <div id="elementA"> already defined!? Nope, Javascript is not broken. What happened is that HTML files load in a top-to-bottom, left-to-right manner.

The <script> is loaded first, and ran before <div id="elementA"> is even rendered – This is how getElementById("elementA") 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.

 

 

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

4-get-element.html
<!-- (A) THE HTML ELEMENTS -->
<div id="elementA">Foo Bar!</div>
<input type="text" name="elementB" value="Hello World!"/>
<div class="elementC">Foo Bar!</div>
<p id="elementD">
  John Doe is <strong>not</strong> John Wick.
</p>

<script>
// (B) GET BY ID
var element = document.getElementById("elementA");
console.log(element); // ELEMENT

// (C) GET BY NAME
var element = document.getElementsByName("elementB");
console.log(element); // NODE LIST
 
// (D) GET BY CSS CLASS
element = document.getElementsByClassName("elementC");
console.log(element); // HTML COLLECTION
 
// (E) GET BY TAG NAME
element = document.getElementsByTagName("div");
console.log(element); // HTML COLLECTION
 
// (F) GET BY QUERY SELECTOR
element = document.querySelector("#elementD strong");
console.log(element); // ELEMENT
 
// (G) GET BY QUERY SELECTOR (MULTIPLE SELECTORS)
element = document.querySelectorAll("div.elementC, p#elementD");
console.log(element); // NODE LIST
 
/* USE FOR TO LOOP THROUGH THE COLLECTIONS + LIST
for (let el of element) { console.log(el); }
</script>

Getting elements by the id is not the only way in Javascript. There are plenty more that you should take note of.

Method Description Reference
getElementById(ID) Get the HTML element with the given ID. Click Here
getElementByName(NAME) Get the HTML element with the given name. Click Here
getElementsByClassName(CSS) Get all elements with the given CSS class name. Click Here
getElementsByTagName(TAG) Get all elements with the given tag name. Click Here
querySelector(QUERY) Get all elements by a given CSS selector. Click Here
querySelectorAll(QUERY, QUERY) The same as above, except that it takes multiple selectors separated by a comma. Click Here

 

 

ART OF CREATING ELEMENTS

5-create-element.html
<!-- (A) EMPTY LIST -->
<ul id="thelist"></ul>
 
<script>
window.addEventListener("load", function(){
  // (A) GET PARENT
  var parent = 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
    parent.appendChild(li);
  }
});
</script>

Following up with the previous example (again), here is when it makes sense to create elements – When we need to dynamically create list items.

Method / Property Description Reference
document.createTextNode(TEXT) Create a new text node. Click Here
document.createElement(TAG) Create a new HTML element. Click Here
NODE.id Get or set the id of an element. Click Here
NODE.classList The list of CSS classes that the element has. Click Here
NODE.classList.add(CLASS) Add a new CSS class to the element.
NODE.classList.remove(CLASS) Remove a CSS class from the element.
NODE.classList.toggle(CLASS) Toggle the CSS class on the element.
NODE.style.STYLE Get or set a particular CSS style on the element. Click Here
NODE.appendChild(CHILD) Append a child to the end of the element. Click Here

 

 

USEFUL 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

Between directly changing with innerHTML and creating elements createElement() – Which is better? Personally, I have no preference. It is only a matter of which makes sense more in various different situations.

  • 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

How To Add HTML Code In Javascript (click to enlarge)

 

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

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