How to get current html page title with javascript

JavascriptTitle

Javascript Problem Overview


I'm trying to get the plain html page title with javascript.

I use firefox and with

document.title 

I get extra "- Mozilla Firefox" to the end of the title. I know it would be easy to get rid of this by modifying string but if they change text, use different format etc or some other browser modifies this differently I have extra text there again.

So, is there any cross browser way to get the plain tag content with javascript? Jquery solution is ok.</p>

Javascript Solutions


Solution 1 - Javascript

One option from DOM directly:

$(document).find("title").text();

Tested only on chrome & IE9, but logically should work on all browsers.

Or more generic

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

Solution 2 - Javascript

try like this

$('title').text();

Solution 3 - Javascript

Like this :

jQuery(document).ready(function () {
    var title = jQuery(this).attr('title');
});

works for IE, Firefox and Chrome.

Solution 4 - Javascript

$('title').text();

returns all the title

but if you just want the page title then use

document.title

Solution 5 - Javascript

You can get it with plain JavaScript DOM methods.The concept is easy:

  1. Retrieve title element from DOM.

  2. Get its content using innerHTML or innerText.

So:

const titleElement = document.getElementsByTagName("title")
const title = titleElement.innerText

console.log(title) // The title of the HTML page.

To retrieve, you can use other methods such as querySelector, or adding an id to title, getElementById.

Solution 6 - Javascript

To get title and save it to a constant use:

const { title } = document;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmikkomView Question on Stackoverflow
Solution 1 - JavascriptMarcusView Answer on Stackoverflow
Solution 2 - JavascriptMikeView Answer on Stackoverflow
Solution 3 - JavascriptJuSchzView Answer on Stackoverflow
Solution 4 - JavascriptFrancescoView Answer on Stackoverflow
Solution 5 - JavascriptCan DurmusView Answer on Stackoverflow
Solution 6 - JavascriptchovyView Answer on Stackoverflow