Question

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.

Was it helpful?

Solution

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).

OTHER TIPS

If you're looking into changing the title of the document, which is in the markup, use:

document.title = 'New Title';

Your code works with some correction, and it works in a more general case:

document.getElementsByTagName('title')[0]='New Title';

However, it doesn't really change the document title, like the first solution.

document.title stores the title by default, and unless you are running JavaScript on HTML that isn't from the current page, it is usually simplest to just use that.

However, the code you wanted to write in bare JavaScript was:
document.getElementsByTagName('title')[0].innerHTML;

If you are already using jQuery, you can use $(document).find('title').text(); to set your own variable.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top