668

I have a webpage that implements a set of tabs each showing different content. The tab clicks do not refresh the page but hide/unhide contents at the client side.

Now there is a requirement to change the page title according to the tab selected on the page ( for SEO reasons ). Is this possible? Can someone suggest a solution to dynamically alter the page title via javascript without reloading the page?

2
  • 10
    document.title = "new title"; but if page have iframes, you may use: window.top.document.title Apr 12, 2021 at 8:25
  • How are you making your set of tabs individual and distinct?
    – Sunil Shah
    May 7, 2021 at 3:41

20 Answers 20

896

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.

13
  • 34
    If you're using html5's pushState to change history when updating your page already, why not update the title aswell. If set up properly crawlers would still get the right results and you'll still want the user to see the title matching the view he's on. For most web-apps etc. it seems like a good sollution to keep using this. I might have overlooked a different function though? Aug 7, 2013 at 8:55
  • 37
    This isn't quite true. Google does index javascript changes to document.title. See searchengineland.com/…
    – CpnCrunch
    Oct 29, 2015 at 1:11
  • 8
    @CpnCrunch is correct! Google will index the title that was changed by JavaScript. I haven't tested on other search bots.Don't always assume a bot doesn't execute JavaScript. I created a new answer below, and then realized that simply showing and hiding tabs without changing the URL makes this more complex.
    – yazzer
    Nov 25, 2015 at 21:24
  • 10
    @CpnCrunch is correct. This is 2016. SEO has changed a lot and Google and other search engines are adapting to single page apps and javascript in general.
    – pilau
    Jan 5, 2016 at 17:50
  • 44
    So it means this answer is quite obsolete. StackOverflow should now add "Obsolete" feature for answers :D Mar 14, 2016 at 7:42
212

I want to say hello from the future :) Things that happened recently:

  1. Google now runs javascript that is on your website1
  2. People now use things like React.js, Ember and Angular to run complex javascript tasks on the page and it's still getting indexed by Google1
  3. you can use html5 history api (pushState, react-router, ember, angular) that allows you to do things like have separate urls for each tab you want to open and Google will index that1

So to answer your question you can safely change title and other meta tags from javascript (you can also add something like https://prerender.io if you want to support non-Google search engines), just make them accessible as separate urls (otherwise how Google would know that those are different pages to show in search results?). Changing SEO related tags (after user has changed page by clicking on something) is simple:

if (document.title != newTitle) {
    document.title = newTitle;
}
$('meta[name="description"]').attr("content", newDescription);

Just make sure that css and javascript is not blocked in robots.txt, you can use Fetch as Google service in Google Webmaster Tools.

1: http://searchengineland.com/tested-googlebot-crawls-javascript-heres-learned-220157

2
  • 3
    Hello to the future! Wanted to ask why are you still using jQuery there and what for this comparison needed (document.title != newTitle)
    – Volod
    Dec 4, 2020 at 17:31
  • 2
    it was the future in 2016 mind you :) comparison is there just in the case if the title didn't change when navigating between pages, I guess description could have stayed the same, but it was just intended as short demostration
    – JLarky
    Dec 5, 2020 at 5:56
69

Use document.title.

See this page for a rudimentary tutorial as well.

6
  • 16
    love the link, it's got netscape navigator screenshots :) Jun 13, 2012 at 4:43
  • I would hope Spiders don't use javascript. Good way to send google malicious code? Aug 3, 2012 at 18:08
  • @AdrianoVaroliPiazza It may be useless, but it works and will help people coming from search engines. No need to downvote if it's the correct answer! Jun 26, 2015 at 19:24
  • @its_notjack It's not. It might be the correct answer for another question. Jun 26, 2015 at 21:27
  • 1
    Well this topic came first for me when I typed "javascript change title" in Google. I'm developing a web app so I don't care about SEO. May 27, 2016 at 10:26
54

The code is
document.title = 'test'

5
  • 3
    I use top.document.title to reference to window itself (I have framesets...)
    – Dror
    Jan 5, 2009 at 15:29
  • 2
    @AdrianoVaroliPiazza no need to go -1 though, what about applications which do not require SEO or what about websites which actually make use of some HTML5 functions. I mean if you set up your website properly and make use of ajax and have a fallback for non-js/crawlers this will only speedup the user experiance and also keep the matching title visible. Seems like a good idea to me. Aug 7, 2013 at 8:59
  • Don't you need to add a ; to the end?
    – MineCMD
    Mar 3, 2016 at 21:26
  • 1
    @MineCMD, a semicolon (;) is only required if you have multiple commands on a single line. Assuming that you don't have something holding the command open (a dot, quote, double quote, left brace, etc.) then a newline is considered to be the ending of the command. I'm not sure how true this is in the case of old browsers but it has proven to be true in recent versions of both Chrome and Firefox. (I don't use IE or Edge so am unable to say on them)
    – Wayne
    Mar 27, 2016 at 6:57
  • @Wayne Somewhat-correct; there are some edge cases where ASI leads to unexpected (by most) behavior, particularly if you're returning an anonymous object. May 7, 2018 at 19:49
47

I can't see how changing the page title via Javascript will help SEO. Most (or all) search bots do not run Javascript and will only read the initially loaded title that is the mark-up.

If you want to help SEO, then you will need to change the page title in the back-end and serve different versions of the page.

7
  • 3
    agreed - this won't help SEO at all, as the crawlers won't do anything with your JS
    – annakata
    Jan 5, 2009 at 15:32
  • Maybe they just want one title but all the content on the SE, but then a more friendly organization of data once you're on the page?
    – Kev
    Jan 5, 2009 at 15:32
  • well then they're very much going against the whole concept of SEO
    – annakata
    Jan 5, 2009 at 15:39
  • 4
    Yeah not really good for SEO but good for the end user when bookmarking etc, for example updating a page title when the hash in the URL changes, or when using HTML5/JS window.history its good to update page title as well as URL
    – rmorse
    Apr 29, 2013 at 11:36
  • See googles own documentation on crawling javascript applications developers.google.com/webmasters/ajax-crawling
    – codewizard
    Oct 29, 2014 at 17:10
22

There are many ways you can change the title, the main two, are like so:

The Questionable Method

Put a title tag in the HTML (e.g. <title>Hello</title>), then in javascript:

let title_el = document.querySelector("title");

if(title_el)
    title_el.innerHTML = "World";

The Obviously Correct Method

The simplest of all is to actually use the method provided by the Document Object Model (DOM)

document.title = "Hello World";

The former method is generally what you would do to alter tags found in the body of the document. Using this method to modify meta-data tags like those found in the head (like title) is questionable practice at best, is not idiomatic, not very good style to begin with, and might not even be portable. One thing you can be sure of, though, is that it will annoy other developers if they see title.innerHTML = ... in code they are maintaining.

What you want to go with is the latter method. This property is provided in the DOM Specification specifically for the purpose of, as the name suggests, changing the title.

Note also that if you are working with XUL, you may want to check that the document has loaded before attempting to set or get the title, as otherwise you are invoking undefined behavior (here be dragons), which is a scary concept in its own right. This may or may not happen via JavaScript, as the docs on the DOM do not necessarily pertain to JavaScript. But XUL is a whole 'nother beast, so I digress.

Speaking of .innerHTML

Some good advice to keep in mind would be that using .innerHTML is generally sloppy. Use appendChild instead.

Although two cases where I still find .innerHTML to be useful include inserting plain text into a small element...

label.innerHTML = "Hello World";
// as opposed to... 
label.appendChild(document.createTextNode("Hello World"));
// example:
el.appendChild(function(){
    let el = document.createElement("span");
    el.className = "label";
    el.innerHTML = label_text;
    return el;
}());

...and clearing out a container...

container.innerHTML = "";
// as opposed to... umm... okay, I guess I'm rolling my own
[...container.childNodes].forEach(function(child){
    container.removeChild(child);
});
3
  • 1
    I found the perfect word for the caveat with method 1: undefined behavior. Feb 19, 2014 at 18:17
  • 1
    This absolutely should be downvoted. Method 1 is undefined behavior, like noted above (and no amount of disclaimers will justify mentioning it); also, document.querySelector.apply, seriously? Feb 29, 2016 at 7:31
  • 4
    @AndreyTarantsov no amount of disclaimers will justify mentioning it? How about mentioning it so that people know what NOT to do? We learn from our mistakes, so telling someone not to mention something that is a mistake, is bad advice. Also, this is a really old answer (literally one of the first answers I wrote on this site), so that "seriously?" was unnecessary. You can't possibly know what has changed in my knowledge and experience over the past three years. Feb 29, 2016 at 8:02
12

Modern crawlers are able to parse dynamically-generated content in the DOM, so using document.title = ... is perfectly fine.

11

Using the document.title is how you would accomplish it in JavaScript, but how is this supposed to assist with SEO? Bots don't generally execute javascript code as they traverse through pages.

4

You'll have to re-serve the page with a new title in order for any crawlers to notice the change. Doing it via javascript will only benefit a human reader, crawlers are not going to execute that code.

3

Maybe you can load on your title all the tabs titles in one string, and then once you load one of the tabs change the title via javascript

ex: at first set your title to

my app | description | contact | about us | 

once you load one of the tabs run:

document.title = "my app | tab title";
3

for those looking of the npm version of it, there is an entire library for this:

npm install --save react-document-meta


import React from 'react';
import DocumentMeta from 'react-document-meta';

class Example extends React.Component {
  render() {
    const meta = {
      title: 'Some Meta Title',
      description: 'I am a description, and I can create multiple tags',
      canonical: 'http://example.com/path/to/page',
      meta: {
        charset: 'utf-8',
        name: {
          keywords: 'react,meta,document,html,tags'
        }
      }
    };

    return (
      <div>
        <DocumentMeta {...meta} />
        <h1>Hello World!</h1>
      </div>
    );
  }
}

React.render(<Example />, document.getElementById('root'));
3

Use document.title. It will be useful for most things, but it will destroy SEO on your website.

Example:

document.write("title - " + document.title + "<br>");
document.title = "New title here!";
// Notice: this will defeat purpose of SEO. Not useful for SEO-friendly sites.
document.write("title - " + document.title + "<br>");
body {
  font-family: Consolas, 'Courier New', monospace;
}
<!DOCTYPE html>
<html>
  <head><title>Old title</title></head>
  <body><p>
    Lorem ipsum dolor sit amet, at movet detraxit mediocritatem eam, nam iusto abhorreant ne. Ei pro          debet adolescens voluptaria, eu minim scaevola conceptam vel. Vim ea torquatos constituto                complectitur, usu eu civibus insolens eleifend. Ex ubique quaerendum his.

  </p></body>
</html>

1
  • Why will it destroy SEO? Oct 18, 2022 at 5:44
2

One way that comes to mind that may help with SEO and still have your tab pages as they are would be to use named anchors that correspond to each tab, as in:

http://www.example.com/mypage#tab1, http://www.example.com/mypage#tab2, etc.

You would need to have server side processing to parse the url and set the initial page title when the browser renders the page. I would also go ahead and make that tab the "active" one. Once the page is loaded and an actual user is switching tabs you would use javascript to change document.title as other users have stated.

2

You can use JavaScript. Some bots, including Google, will execute the JavaScript for the benefit of SEO (showing the correct title in the SERP).

document.title = "Google will run this JS and show the title in the search results!";

However, this is more complex since you are showing and hiding tabs without refreshing the page or changing the URL. Maybe adding an anchor will help as stated by others. I may need to retract my answer.

Articles showing positive results: http://www.aukseo.co.uk/use-javascript-to-generate-seo-friendly-title-tags-1275/ http://www.ifinity.com.au/2012/10/04/Changing_a_Page_Title_with_Javascript_to_update_a_Google_SERP_Entry

Don't always assume a bot won't execute JavaScript. http://searchengineland.com/tested-googlebot-crawls-javascript-heres-learned-220157 Google and other search engines know that the best results to index are the results that the actual end user will see in their browser, including JavaScript.

2

Since search engines ignore most javascript, you will need to make it so that search engines can crawl using the tabs without using Ajax. Make each tab a link with an href that loads the entire page with that tab selected. Then the page can have that title in the tag.

The onclick event handler can still load the pages via ajax for human viewers.

To see the pages as most search engines see them, turn off Javascript in your browser, and try to make it so that clicking the tabs will load the page with that tab selected and the correct title.

If you are loading via ajax and you want to dynamically change the page title with just Javascript, then do:

document.title = 'Put the new title here';

However, search engines will not see this change made in javascript.

2
  • 2
    "To see the pages as Google sees them, turn off Javascript in your browser, and try to make it so that clicking the tabs will load the page with that tab selected and the correct title." - this is a very good approach when developing SEO friendly AJAX-heavy websites.
    – John Weisz
    Mar 14, 2015 at 16:57
  • 1
    On one of my sites, Google has indexed tons of documents which were discoverable only via ajax. Good approach, but don't rely on it as adverse solution if you want to hide it from crawlers. Jan 15, 2021 at 19:12
0

But in order to get the SEO befits

You need to do a page reload when the page changes so that the search engine's see the different titles etc.

So make sure the page reload works first then add document.title changes

0

I just want to add something here: changing the title via JavaScript is actually useful if you're updating a database via AJAX, so then the title changes without you having to refresh the page. The title actually changes via your server side scripting language, but having it change via JavaScript is just a usability and UI thing that makes the user experience more enjoyable and fluid.

Now, if you're changing the title via JavaScript just for the hell of it, then you should not be doing that.

0

Google mentioned that all js files rendered but in real, I've lost my title and another meta tags which had been provided by Reactjs on this website and actually lost my position on Google! I've searched a lot but it seems that all pages must have pre-rendered or using SSR(Server Side Rendering) to have their SEO-friendly protocole!
It expands to Reactjs, Angularjs , etc.
For short, Every page that has view page source on browser is indexed by all robots, if it's not probably Google can index but others skip indexing!

-2

The simplest way is to delete <title> tag from index.html, and include

<head>
<title> Website - The page </title></head>

in every page in the web. Spiders will find this and will be shown in search results :)

-6

I use a seperate header and include it using php, in the header i use:

<?php
if (!isset($title)){
    $title = "Your Title";
  }
  else {
    $title = $title;
  }
 ?>
<head>
<title><?php echo $title; ?></title>

Then in each page I use:

<?php
  $title = "Your Title - Page";
  include( "./header.php" );
?>

Not the answer you're looking for? Browse other questions tagged or ask your own question.