How to create an H1 element with JavaScript

To create an H1 element in JavaScript we need to create 2 elements. The actual H1 element, and a text element. When we have done this we need to append the text element to the H1 element. Now the H1 element contains the text from the text element. After we have done this we can append the H1 element to the document body to display the H1 element with the text.

Steps to create an H1 element in JavaScript

  1. Create the actual H1 element
  2. Create a text element with the text you want to display in the H1 tag
  3. Append the text node to the H1 tag
  4. Append the H1 element to the document body to display its contents

Example to create an H1 element and add it to the document

 
var h = document.createElement("H1"); // Create the H1 element 
var t = document.createTextNode("Your H1 text"); // Create a text element 
h.appendChild(t); // Append the text node to the H1 element 

document.body.appendChild(h); // Append the H1 element to the document body 

We can go one step further and create a function of the above code so you can use it more than one time without repeating yourself.

How to make a function that creates an H1 element

function createH1Element(text) 
{
	var h = document.createElement("H1");
	var t = document.createTextNode(text); 
	h.appendChild(t); 
	document.body.appendChild(h);
} 

createH1Element("First H1");
createH1Element("Second H1");

The code above will display two H1 headings with the text “First H1” and “Second H1” by using the same function. This is the way you can dynamically create H1 headings with or without function in JavaScript.

advertisement