Getting and Setting the Document Title using JavaScript

JavaScript provides a straightforward way to both retrieve and set the title of a webpage. In this article, we'll explore how to use JavaScript to get or set the document title.

Getting the Document Title

To obtain the current document title, you can simply access the document.title property. This property represents the title of the current HTML document.

// Getting the document title
const currentTitle = document.title;
console.log('Current document title:', currentTitle);

In this code:

Setting the Document Title

To dynamically set the document title, you can assign a new value to the document.title property.

// Setting the document title
const newTitle = 'New Page Title';
document.title = newTitle;
console.log('Document title has been set to:', newTitle);

In this code:

Example: Dynamically Updating Document Title

Let's create a complete example where a button click triggers the update of the document title.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document Title Example</title>
  <style>
    /* Optional styling for better presentation */
    body {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 100vh;
      margin: 0;
    }

    button {
      padding: 10px;
      font-size: 16px;
      cursor: pointer;
    }
  </style>
</head>
<body>

  <button onclick="updateDocumentTitle()">Update Document Title</button>

  <script>
    // Function to update the document title
    function updateDocumentTitle() {
      const newTitle = 'Dynamic Title Change';
      document.title = newTitle;
      console.log('Document title has been set to:', newTitle);
    }
  </script>
</body>
</html>

In this example:

Browser Compatibility

The ability to get and set the document title using document.title is widely supported in modern browsers. However, always consider the compatibility of your web application with various browsers to ensure a consistent user experience.

Conclusion

Managing the document title is essential for providing users with relevant and contextual information about the webpage. JavaScript's document.title property makes it easy to dynamically retrieve and update the title of the document, allowing for a more interactive and user-friendly web experience. Incorporate these techniques into your projects to enhance the flexibility and responsiveness of your webpages.