HTML DOM header object


The HTML DOM header object is associated with the HTML <header> element that introduced in HTML 5. Using the header object we can create and access <header> element using the createElement() and getElementById() method respectively.

Syntax

Following is the syntax for −

Creating a header object −

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

Example

Let us look at an example for the HTML DOM header object −

<!DOCTYPE html>
<html>
<body>
<h1>Header object example</h1>
<p>Create a header element by clicking the below button</p>
<button onclick="headerCreate()">CREATE</button>
<script>
   function headerCreate() {
      var h = document.createElement("HEADER");
      document.body.appendChild(h);
      var h2 = document.createElement("H2");
      var txt = document.createTextNode("Header element containing a h2 element is now created");
      h2.appendChild(txt);
      h.appendChild(h2);
   }
</script>
</body>
</html>

Output

This will produce the following output −

On clicking the CREATE button −

In the above example −

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

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

The headerCreate() method creates a header element using the createElement() method upon document object and assigns it to variable h. It then calls the appendChild() method on the document body to append the header as a child to document body. Using the same method above we create an <h2> element and a text node for it using the createTextNode() method of the document object.

The text node is appended to the <h2> element using the appendChild() method. Finally the <h2> element along with the text node are appended as child of the header element using the appendChild() method −

function headerCreate() {
   var h = document.createElement("HEADER");
   document.body.appendChild(h);
   var h2 = document.createElement("H2");
   var txt = document.createTextNode("Header element containing a h2 element is now created");
   h2.appendChild(txt);
   h.appendChild(h2);
}
raja
Published on 09-Aug-2019 12:42:07
Advertisements