We can create a new h1 element with JavaScript by using the createElement() method along with the innerHTML property.
var newh1 = document.createElement("h1");
newh1.innerHTML = "This is a new h1 element."
And that’s it. Let’s go over creating a new h1 element with JavaScript and adding it to the DOM.
In this simple example, we will have some very basic HTML code containing some paragraphs. We will create a new h1 element using JavaScript and add it to our HTML above the paragraphs using the insertBefore() method.
Here is our HTML code:
We will insert a new h1 tag above this paragraph.
This is some text in a paragraph tag.
This is what our HTML will look like before we add the new h1 element.
We will insert a new h1 tag above this paragraph.
This is some text in a paragraph tag.
So we will use our JavaScript code from above along with the insertBefore() method to add a new h1 element to the div, #div1.
var newh1 = document.createElement("h1");
newh1.innerHTML = "This is a new h1 element"
var divToMoveTo = document.getElementById("div1");
divToMoveTo.insertBefore(newh1, divToMoveTo.children[0]);
We will insert a new h1 tag above this paragraph.
This is some text in a paragraph tag.
As we will see below, this can be done much faster and easier using jQuery.
Creating and Adding a New h1 Element With jQuery
If we use jQuery, we can very easily add a new h1 element with the use of the prepend() method.
Here is our same HTML setup:
We will insert a new h1 tag above this paragraph.
This is some text in a paragraph tag.
We will insert a new h1 tag above this paragraph.
This is some text in a paragraph tag.
And here is our new JavaScript code making use of the jQuery prepend() method.
$("#div2").prepend("
This is a new h1 element
");
If you are using WordPress, don’t forget to change the $ to jQuery as below:
jQuery("#div2").prepend("
This is a new h1 element
");
We will insert a new h1 tag above this paragraph.
This is some text in a paragraph tag.
As you can see, this is much easier done with jQuery.
Hopefully this article has been useful for you to understand how you would create a new h1 element with JavaScript.