HTML DOM Heading object


The HTML DOM Heading object is associated with the HTML heading elements ranging from <h1> to <h6>. Using the heading object we can create and access heading element with the createElement() and getElementById() method respectively.

Syntax

Following is the syntax for −

Creating a Heading object −

var p = document.createElement("H1");

Example

Let us look at an example for the Heading object −

Live Demo

<!DOCTYPE html>
<html>
<body>
<h1>Heading object example</h1>
<p>Create a h1 element by clicking the below button</p>
<button onclick="createH1()">CREATE</button>
<script>
   function createH1() {
      var h = document.createElement("H1");
      var txt = document.createTextNode("H1 element has been created");
      h.appendChild(txt);
      document.body.appendChild(h);
   }
</script>
</body>
</html>

Output

This will produce the following output −

On clicking the CREATE button −

In the above example −

We have first created a button CREATE that will execute the headerCreate() method when clicked by the user −

<button onclick="createH1()">CREATE</button>

The CreateH1() method creates an <h1> heading element using the createElement() method on document object and assigns it to variable h. We then create a text node for it using the createTextNode() method of the document object. The text node is appended to the <h1> element using the appendChild() method. Finally the <h1> element along with the text node are appended as child of the document’s body using the appendChild() method −

function createH1() {
   var h = document.createElement("H1");
   var txt = document.createTextNode("H1 element has been created");
   h.appendChild(txt);
   document.body.appendChild(h);
}

Updated on: 19-Feb-2021

337 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements