how to get page title?

L

laredotornado

Hello,
How do I use Javasript to get the <TITLE> element of a web page?
If anyone can supply a cross browser way (IE 5.5+, Firefox 1+), it is
most appreciated.

Dave
 
M

Martin Honnen

How do I use Javasript to get the <TITLE> element of a web page?

document.title gives you the text content of the <title> element. You
can also set document.title in most current browsers.

The element itself can be accessed like any other element using e.g.
var titleElement;
if (document.getElementsByTagName) {
titleElement = document.getElementsByTagName('title')[0];
if (titleElement) {
// use titleElement here e.g.
alert(titleElement.nodeName);
}
}
 
R

RobG

Danny said:
Either as Martin indicated using DOM, or using:
document.title='YOUR TITLE HERE';

document.title is included in the DOM HTMLDocument interface, so to that
extent it is 'DOM':

<URL:http://www.w3.org/TR/2000/WD-DOM-Level-2-HTML-20001113/html.html#ID-26809268>

It is both a 'getter' and a 'setter' and is generally displayed in a
browser's window title bar.


Using Martin's getElementsByTagName method will return a reference to
the title element, but the actual value is the content, not the element
itself. IE refuses to believe that there are any nodes inside the title
- but it will return a value for innerHTML.

So to get the actual text content of the title element you need to
access the firstChild, or for IE use innerHTML:

function showTitle()
{
var t = document.getElementsByTagName('title')[0];
if ( !!t.childNodes.length ) {
alert( t.firstChild.data );
} else if ( t.innerHTML ) {
alert( t.innerHTML );
}
}

You can set the value of the element much the same way, but IE will not
let you modify the innerHTML:

function changeTitle( txt ){
var t = document.getElementsByTagName('title')[0];
if ( !!t.childNodes.length ) {
t.firstChild.data = txt;
} else if ( t.innerHTML ) {
alert( 'Out of luck' );
// t.innerHTML = txt; // uncomment to see error in IE
}

Changing the title element this way does not seem to modify the title
shown in the window title bar (Firefox & IE).

Given all the above, using document.title as a getter and setter gets a
big thumbs up:

function showTitle(){
alert( document.title );
}

function changeTitle( txt ){
document.title = txt;
alert( 'Title changed to ' + document.title );
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,682
Members
48,796
Latest member
Greg L.

Latest Threads

Top