How can I get the title of an HTML page with JavaScript?
Asked
Active
Viewed 2.9e+01k times
272
-
1Note 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 Answers
431

Pikamander2
- 7,332
- 3
- 48
- 69

ZA.
- 10,107
- 10
- 37
- 39
-
3
-
49
-
4
-
2This 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
-
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>

Marcell Kraszni
- 1
- 1