DEV Community

Tushar
Tushar

Posted on

3

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.

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs