DEV Community

Tushar
Tushar

Posted on

Creating and Appending a Heading in JavaScript

In this blog post, we'll cover the basics of creating a heading element using JavaScript and how to append it to an existing element in your HTML document. This is a fundamental skill for manipulating the DOM (Document Object Model) and dynamically updating the content of your web pages.

Creating a Heading Element with JavaScript

First, let's create a heading element using JavaScript. We'll use the document.createElement method to create an h1 element and then set its content using innerHTML.

Here's how you can do it:

const Heading = document.createElement("h1");
Heading.innerHTML = "Hello World";

Enter fullscreen mode Exit fullscreen mode

Explanation:

  • document.createElement("h1"): This method creates an h1 element.
  • Heading.innerHTML = "Hello World": This line sets the inner HTML of the h1 element to "Hello World".

Appending the Heading to the Root Element

Now that we've created our heading element, we need to append it to a specific part of our HTML document. Let's assume we have a div element with the id root in our HTML. We'll use the getElementById method to select this element and then append our heading to it using appendChild.

Here's the complete code:

const root = document.getElementById("root");
root.appendChild(Heading);

Enter fullscreen mode Exit fullscreen mode

Explanation:

  • document.getElementById("root"): This method retrieves the element with the id root.
  • root.appendChild(Heading): This line appends our heading element to the root element.

By executing this code, the "Hello World" heading will be inserted into the div with the id root.

Top comments (0)