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!

 

 

TLDR – QUICK SLIDES

[web_stories_embed url=”https://code-boxx.com/web-stories/how-to-add-html-code-in-javascript/” title=”How To Add HTML Code In Javascript” poster=”https://code-boxx.com/wp-content/uploads/2021/11/STORY-JS-20230518.webp” width=”360″ height=”600″ align=”center”]

Fullscreen Mode – Click Here

 

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

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

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

  • (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

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

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

  • (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).
  • (D) If you just want to append text, create a text node instead – var TEXT = document.createTextNode("TEXT").

 

 

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

3-get-element.html
<!-- (A) THE HTML ELEMENTS -->
<div id="demoA">Foo Bar!</div>
<input type="text" name="demoB" value="Hello World!"/>
<span class="demoC">Foo Bar!</span>
<u>DemoD</u>
<p id="demoE">
  John Doe is <strong>not</strong> John Wick.
</p>

<script>
// (B) GET BY ID
var demoA = document.getElementById("demoA");
console.log(demoA); // <div id="demoA">

// (C) GET BY NAME
var demoB = document.getElementsByName("demoB");
console.log(demoB); // node list - [<input name="demoB">]
 
// (D) GET BY CSS CLASS
var demoC = document.getElementsByClassName("demoC");
console.log(demoC); // html collection - [<span class="demoC">]
 
// (E) GET BY TAG NAME
var demoD = document.getElementsByTagName("u");
console.log(demoD); // html collection - [<u>demoD</u>]
 
// (F) GET BY QUERY SELECTOR
var demoE = document.querySelector("#demoE strong");
console.log(demoE); // <strong>not</strong>
 
// (G) GET BY QUERY SELECTOR (MULTIPLE SELECTORS)
var demoF = document.querySelectorAll("span.demoC, p#demoE");
console.log(demoF); // node list - [<span class="demoC">, <p id="demoE">]
 
/* 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

 

 

SET HTML/CSS PROPERTIES

4-set-properties.html
<!-- (A) EMPTY LIST -->
<ul id="thelist"></ul>
 
<script>
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);
  }
});
</script>

Remember the “create and append HTML element” example? Yes, we can also set the HTML/CSS properties in Javascript too.

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

 

TAKE EXTRA NOTE OF THE LOADING ORDER!

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

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 <div id="demo"> 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="demo"> 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.

 

SORRY FOR THE ADS...

But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.

Buy Me A Coffee Code Boxx eBooks

 

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

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 *