272

How can I get the title of an HTML page with JavaScript?

Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177
ZA.
  • 10,107
  • 10
  • 37
  • 39
  • 1
    Note that there's a slight difference between using `document.title` and accessing the `title` element directly, see [here](https://stackoverflow.com/q/65241128/2604492). – Paul Dec 10 '20 at 22:02

4 Answers4

431

Use document.title:

console.log(document.title)
<title>Title test</title>

MDN Web Docs

Pikamander2
  • 7,332
  • 3
  • 48
  • 69
ZA.
  • 10,107
  • 10
  • 37
  • 39
  • 3
    HTML5 version ;) `` – OregonTrail Jun 12 '13 at 22:11
  • 49
    @OregonTrail wut?, if `console.log`, then `alert` anyway? – Petah Jun 13 '13 at 00:23
  • 4
    What's the point of including ` – Michał Perłakowski Dec 27 '15 at 15:24
  • 2
    This answer says that `document.title` returns the HTML title element, but as the code snippet shows, it does not do that. It returns the text that is inside the HTML title element. That's a pretty big difference. – zumafra Jul 31 '20 at 15:40
18

Put in the URL bar and then click enter:

javascript:alert(document.title);

You can select and copy the text from the alert depending on the website and the web browser you are using.

No Mercy
  • 213
  • 2
  • 2
13

Can use getElementsByTagName

var x = document.getElementsByTagName("title")[0];

alert(x.innerHTML)

// or

alert(x.textContent)

// or

document.querySelector('title')

Edits as suggested by Paul

SuperNova
  • 25,512
  • 7
  • 93
  • 64
  • 5
    This answer is great if your parsing an HTML doc – Mattwmaster58 Sep 01 '18 at 04:05
  • 1. Use `textContent` instead of `innerHTML` - the title is pure text. 2. Use `querySelector("title")` instead of `getElementsByTagName("title")[0]` - see [this answer](https://stackoverflow.com/a/54952474/2604492). – Paul Dec 11 '20 at 11:28
0

this makes the h1 element the page title. this shows how capable can be javascript for small and big projects.

document.getElementById("text").innerText = document.title;
<title>hello world</title>
<h1 id="text"></h1>