HTML DOM head property


The HTML DOM head property is associated with the HTML <head> element. It is used for returning the <head> element. If there are multiple head elements then it will return the first head element. It is a read-only property.

Syntax

Following is the syntax for the head property −

document.head

Example

Let us look at an example for the HTML DOM head property −

<!DOCTYPE html>
<html>
<head>
<title>My title</title>
</head>
<body>
<h1>head property example</h1>
<p>Get this document title by clicking on the below button</p>
<button onclick="getTitle()">Get Title</button>
<p id="Sample"></p>
<script>
   function getTitle() {
      var x = document.head.firstElementChild.innerHTML;
      document.getElementById("Sample").innerHTML = "The title of this document is: "+x;
   }
</script>
</body>
</html>

Output

This will produce the following output −


On clicking the “Get Title” button −

In the above example −

We have first created a <head> element that contains a <title> element inside it specifying the title for this web page −

<head>
<title>My title</title>
</head>

We then create a button “Get Title” that will execute the getTitle() method on being clicked by the user.

<button onclick="getTitle()">Get Title</button>

The getTitle() method uses the document head property to get the head element and the firstElementChild property to get its first child element which is the <title> element in our case.

We then use the innerHTML property upon the title element to get the text inside it and display it in the paragraph with id “Sample” using its innerHTML property −

function getTitle() {
   var x = document.head.firstElementChild.innerHTML;
   document.getElementById("Sample").innerHTML = "The title of this document is: "+x;
}
raja
Published on 09-Aug-2019 12:36:49
Advertisements