JavaScript get the <title> element

Progo picture Progo · Jan 19, 2014 · Viewed 14.2k times · Source

I am writing a script that will make the title tag switch messages every few seconds.

I wrote the code but when I tried to run it, I got an error here:

title = document.getElementByTagName("title")

The error I am getting says: TypeError: 'undefined' is not a function (evaluating 'document.getElementByTagName("title")').

The script tag is below the title tag and inside my script tag I have this to make sure the page has fully loaded before the code is ran:

window.addEventListener("DOMContentLoaded", function(){
    //code

Why am I getting an error when I try to get the title tag?

Thank you.

Answer

Quentin picture Quentin · Jan 19, 2014

getElementByTagName isn't a function (unless you write one).

There is a getElementsByTagName function (note Elements is plural) which returns a node list.

It's usually simpler to just use document.title though (which is a string).