0

I would like to change my page title dynamically so that it will match with the value of 'h1' heading element. Need to write a global javascript, which I can use throughout the application for every page. Kindly advice. Thanks in advance

SatAj
  • 1,709
  • 3
  • 24
  • 43
  • 1
    Just out of curiosity, why do you need this? Are you changing your `h1`s dynamically? If not, this should really be done on the backend. And if it is used for SEO purposes, a JS change is usually too late (i.e. the "old" title will be used by search engines). – Steve Jul 16 '14 at 20:56
  • Its a project requirement. – SatAj Jul 16 '14 at 21:34

2 Answers2

3
document.title = $("h1").text();
APAD1
  • 12,726
  • 8
  • 36
  • 67
1

Simply select the correct elements, and assign the text of the h1 to the text of the title:

$('title').text($('h1').text());
David says reinstate Monica
  • 230,743
  • 47
  • 350
  • 385
  • Thanks David. This also works perfectly. How can we take only first

    of the page in case there are multiple

    in the page?

    – SatAj Jul 17 '14 at 16:27
  • Hi David... One more query.. I am searching first h1 tag but I wanted to exlude all the

    present in class "ui-dialog" from this search. Your help will be really appreciated...

    – SatAj Jul 17 '14 at 20:34
  • `$('h1').not('.ui-dialog').text()`, assign the text as before. And you will only ever retrieve the text of the first element from the collection, it sets multiple elements' text, it gets only one (the first). – David says reinstate Monica Jul 17 '14 at 20:43