How to get the title of an HTML page ?
The task is to get the title of the HTML document using javascript. There is a number of ways to do this But Here a few of the most preferred techniques are discussed.
Example 1: This example gets the title of document by using document.title property.
<!DOCTYPE HTML> < html > < head > < title > JavaScript | Get the title of HTML page. </ title > </ head > < body style = "text-align:center;" id = "body" > < h1 style = "color:green;" > GeeksForGeeks </ h1 > < p id = "GFG_UP" style="font-size: 19px; font-weight: bold;"> </ p > < button onClick = "GFG_Fun()" > click here </ button > < p id = "GFG_DOWN" style="color: green; font-size: 24px; font-weight: bold;"> </ p > < script > var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); up.innerHTML = 'Click on button to get the title of HTML document'; function GFG_Fun() { down.innerHTML = document.title; } </ script > </ body > </ html > |
Output:
- Before clicking on the button:
- After clicking on the button:
Example 2: This example gets the title of document by first selecting the title by tag name and then taking the element at index 0. using document.getElementsByTagName() method.
<!DOCTYPE HTML> < html > < head > < title > JavaScript | Get the title of HTML page. </ title > </ head > < body style = "text-align:center;" id = "body" > < h1 style = "color:green;" > GeeksForGeeks </ h1 > < p id = "GFG_UP" style="font-size: 19px; font-weight: bold;"> </ p > < button onClick = "GFG_Fun()" > click here </ button > < p id = "GFG_DOWN" style="color: green; font-size: 24px; font-weight: bold;"> </ p > < script > var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); up.innerHTML = 'Click on button to get the title of HTML document'; function GFG_Fun() { var title = document.getElementsByTagName("title")[0]; down.innerHTML = title.innerHTML; } </ script > </ body > </ html > |
Output:
- Before clicking on the button:
- After clicking on the button: