Search code examples
javascriptpage-title

Dynamically change page title from h1 tag using Javascript


First off, thanks for taking the time to read this question. What a great community Stack Overflow has :)

I need to change the title tag of a page based on the text contained in the h1 element on that page.

I've been searching around, and I have found the "document.title" Javascript function. I've been playing around with it, trying to pull the text from my h1 element that has the class of "Category-H1".

<script type="text/javascript">
    document.title = document.getElementsByClassName("Category-H1");
</script>

However, it is just setting the page title to "[object HTMLCollection]", which as I understand is a null value. Is JS the best was to do this? I know my code is jacked, any tips?

Thanks in advance! - Alex

Edit

I have been informed that line of code returns a collection object and not a string. It was pointed to a code example of:

setTimeout(function () { document.title = "iFinity User Profile - " + document.getElementById("test").outerText; }, 1000); 

However, this code produces a page title of "iFinity User Profile - undefined". I have the h1 element on that page set to the id of "test".


Solution

  • You're almost there.

    [object HTMLCollection] is not a null value--it is the string representation of a collection of html elements. You want to choose the first one and then get the inner html from it.

    document.getElementsByClassName("Category-H1")[0].innerHTML
    

    Also, make sure you do this after the document has loaded. You can either do this by adding the script at the end of your document, or have it run on the onload event of the body.