This blog post will define the procedure for changing the page title in JavaScript.
How to Change the Page Title in JavaScript?
For changing the page title, use the below-given methods:
- document.title property
- querySelector() method
Let’s see how these methods work.
Method 1: Change the Page Title Using document.title Property
The document’s title can be changed or retrieved using the “document. title” attribute. The page’s title can be changed by providing the new name or title as a string to this attribute.
Syntax
Follow the given syntax for using the property “document.title” to change the page title:
Example
Create a button in HTML file that will change the page title on the click event:
Here, the page title of the created HTML page is “Document” that will be changed by clicking on the button:
In JavaScript file, define a function, “changeTitle()” where set the new title for the page that will be changed using the “document.title” attribute:
document.title = 'LinuxHint';
}
Output
The above output shows that the page title is successfully changed on the button click.
Method 2: Change the Page Title Using querySelector() Method
There is another way to change the page title, using the “querySelector()” method with the “textContent” attribute. This method takes a DOM element as an argument and then changes the page’s current title using the textContent property.
Syntax
Use the following syntax to change the page title using the “querySelector()” method:
Example
Define a function “changeTitle()” and set the new title for the page by choosing “title” element in “querySelector()” method:
document.querySelector('title').textContent = 'LinuxHint';
}
Output
It can be observed from the output that the page’s title has been changed using JavaScript.
Conclusion
To change the page title, use the “document.title” property or the “querySelector()” method with the “textContent” property. For changing the page title, the “document.title” attribute is the most widely utilized method. It quickly changes the page’s title, while the second method first fetches the title element and then changes its value This blog post demonstrates the ways to change the title of the page in JavaScript.