Explain Codes LogoExplain Codes Logo

How to get the title of HTML page with JavaScript?

javascript
prompt-engineering
functions
callbacks
Alex KataevbyAlex Kataev·Jan 18, 2025
TLDR

To fetch the page title in JavaScript, use document.title.

console.log(document.title); // Logs the page title to the console

A straightforward solution, compatible across all browsers.

Digging deeper into the topic, let's take a look at how to manage dynamic updates, cross-browser compatibility, and performance optimization when working with the HTML page title.

Tackling dynamic titles

When the webpage is dynamic, the title may change to reflect the page content, user interaction, or server-side updates. JavaScript provides built-in methods to react to these changes:

window.onhashchange = function() { // I solemnly swear that I'm up to no good console.log(document.title); // Marauder's map reveals the changed title! }

If the title changes due to AJAX or React updates, you need to re-fetch the title:

fetch('/dynamic-content').then(() => { console.log(document.title); // Fresh catch of the day });

Accessing the title tag

In certain scenarios, you might need to work with the <title> tag directly, particularly in densely populated <head> sections. Here's how:

var titleTag = document.querySelector('head title'); console.log(titleTag.textContent); // Playing hide and seek with <title>

Alternatives include document.getElementsByTagName('title')[0] or the getElementById('id') method if you assigned an id to the title tag. Remember that robust error handling is crucial to prevent script failures.

Integrating title management in your application

Title management is often a crucial part of the application architecture. The page title is often used in breadcrumbs, hierarchy orders, or SEO optimizations. The below script shows how to synchronize the page title with an h1 tag:

document.getElementById('page-header').textContent = document.title; // Ensuring the twins look the same!

This maintains uniformity between the browser's title bar and the page content.

Cross-browser compatibility

Even though document.title is natively supported by all browsers, some glitches may arise. Always verify the uniformity of your implementation across multiple browsers.

For performance, if the title changes frequently, consider debouncing the title update function to prevent janky experiences.

Advanced title customization techniques

Rethinking standard retrieval and updates, you can explore advanced techniques like binding the title to the data model in frameworks like Vue.js or Angular, enabling reactive title updates:

// Example using Vue.js new Vue({ el: 'title', data: { pageTitle: 'Initial Title' }, watch: { pageTitle(newValue) { document.title = newValue; // Changing hats. } } });