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
Asked
Active
Viewed 1,461 times
0
-
1Just 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 Answers
3
document.title = $("h1").text();

APAD1
- 13,509
- 8
- 43
- 72
-
1Thanks a lot. This works perfectly. How can we take only first
of the page in case there are multiple
– SatAj Jul 17 '14 at 16:25in the page?
-
No problem. You can select only the first instance of an H1 like this: `document.title = $("h1:first").text();` – APAD1 Jul 17 '14 at 16:33
-
-
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:32 -
I think this should work: `document.title = $("h1:not('.ui-dialog h1'):first").text();` – APAD1 Jul 17 '14 at 20:41
1
Simply select the correct elements, and assign the text of the h1
to the text of the title
:
$('title').text($('h1').text());

David Thomas
- 249,100
- 51
- 377
- 410
-
Thanks David. This also works perfectly. How can we take only first
of the page in case there are multiple
– SatAj Jul 17 '14 at 16:27in the page?
-
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 Thomas Jul 17 '14 at 20:43