How to Change a Web Page’s Title Dynamically using JavaScript ?

Given a web page containing the page title and the task is to change the title of a web page dynamically using JavaScript. 

Method 1: Using JavaScript document.title property.

This property is used to set or return the current title of the document. The title of the page can be changed by assigning the new title as a string to this property. This will change the title of the website to the preferred title. 

Syntax: 

newPageTitle = 'The title has changed!';
document.title = newPageTitle;

Example: 

<!DOCTYPE html>
<html>
  
<head>
    <title>
        How to Change a Web Page’s Title Dynamically using JavaScript ?
    </title>
</head>
  
<body>
    <h1 style="color: green">
        Codeyyan
    </h1>
      
    <b>
        How to Change a Web Page’s Title Dynamically using JavaScript ?
    </b>
      
    <p>
        Click on the button to change the page
        title to: "The title has changed!"
    </p>
      
    <button onclick="changePageTitle()">
        Change Page Title
    </button>
      
    <script type="text/javascript">
        function changePageTitle() {
            newPageTitle = 'The title has changed!';
            document.title = newPageTitle;
        }
    </script>
</body>
</html>

Method 2: Using DOM querySelector() Method.

This method is used to select elements in the document. The title element can be selected by specifying the title element in the selector as a parameter. This will return the current title element of the page. The textContent property of an element returns the text content of a specific node. The title of the page can be changed by assigning the required new title as a string to the textContent property. This will change the title of the website to the preferred title. 

Syntax: 

newPageTitle = 'The title has changed!';
document.querySelector('title').textContent = newPageTitle;

Example: 

<!DOCTYPE html>
<html>
  
<head>
    <title>
        How to Change a Web Page’s Title Dynamically using JavaScript ?
    </title>
</head>
  
<body>
    <h1 style="color: green">
        Codegyan
    </h1>
      
    <b>
        How to Change a Web Page’s Title Dynamically using JavaScript ?
    </b>
      
    <p>
        Click on the button to change the page
        title to: "The title has changed!"
    </p>
      
    <button onclick="changePageTitle()">
        Change Page Title
    </button>
      
    <script type="text/javascript">
        function changePageTitle() {
            newPageTitle = 'The title has changed!';
            document.querySelector('title').textContent
                    = newPageTitle;
        }
    </script>
</body>
  
</html>

How to Change a Web Page’s Title Dynamically using JavaScript ?

Published on 05-Feb-2023 15:13:38

You may also like this!