How to Dynamically Change a Web Page'S Title

How to dynamically change a web page's title?

Update: as per the comments and reference on SearchEngineLand
most web crawlers will index the updated title. Below answer is obsolete, but the code is still applicable.

You can just do something like, document.title = "This is the new
page title.";
, but that would totally defeat the purpose of SEO. Most
crawlers aren't going to support javascript in the first place, so
they will take whatever is in the element as the page title.

If you want this to be compatible with most of the important crawlers,
you're going to need to actually change the title tag itself, which
would involve reloading the page (PHP, or the like). You're not going
to be able to get around that, if you want to change the page title in
a way that a crawler can see.

Change HTML title dynamically

  would be recognized as a string itself in JS. You can use the \xa0 character.

document.title = 'Far\xa0\xa0Apart'

How to modify a page title using JavaScript or jQuery?

You can do this:

$('title').text('New title');

There is another jQuery method called html() but that's only suitable when adding content that must be understood as tags. Since titles cannot contain HTML, text() is appropriate.

How to change browser page title dynamically to match it with h1 title in javascript or jQuery?

document.title = $("h1").text();

Dynamic page title with ReactJS

If you need to avoid installing modules, you could do this as helper file, then just import it in module you need and call in componentDidMount

export function seo(data = {}) {
data.title = data.title || 'Default title';
data.metaDescription = data.metaDescription || 'Default description';

document.title = data.title;
document.querySelector('meta[name="description"]').setAttribute('content', data.metaDescription);
}
import React from 'react';
import {seo} from '../helpers/seo';

export default class SomeClass extends Component {
constructor(props) {
super(props);
};

componentDidMount() {
seo({
title: 'This is my title only shown on this page',
metaDescription: 'With some meta description'
});
}

render() {
return <h1>Hello World</h1>;
}
}

You could also just call directly document.title = 'My new title' anywhere, but if you extract it as function you have the option to have default one and just provide override when you want to.

Edit: upon inspecting your code, if you change hhh = pageTitles[i].text; to hhh = pageTitles[i].title; it will work. Would be nice to declare the var outside of the loop. Also would be nice to have default value.



Related Topics



Leave a reply



Submit