How to Get the Title of HTML Page with JavaScript

How to get the title of HTML page with JavaScript?

Use document.title:

console.log(document.title)
<title>Title test</title>

How to get current html page title with 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;

JavaScript get the title element

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

how to get the inner html of the title

You can parse your loaded data to an HTML Content Template, so once you have the data:

/*...*/

let resp = request.responseText;

const tpl = document.createElement('template');
tpl.innerHTML = resp;

document.title = tpl.content.querySelector('title').textContent;

/*...*/

How to dynamically change a web page's title?

Update: as per the comments and reference on SearchEngineLand
most web crawlers will index the updated title. Below answer is obsolete, but the code is still applicable.

You can just do something like, document.title = "This is the new
page title.";
, but that would totally defeat the purpose of SEO. Most
crawlers aren't going to support javascript in the first place, so
they will take whatever is in the element as the page title.

If you want this to be compatible with most of the important crawlers,
you're going to need to actually change the title tag itself, which
would involve reloading the page (PHP, or the like). You're not going
to be able to get around that, if you want to change the page title in
a way that a crawler can see.

How do you get the title of an html page in Javascript

You can get/set document.title.

document.title = "New Title For Page";

Get content of a title element in html using JavaScript

you can use getElementsByTagName() function to get element text property, try this

document.getElementsByTagName("title")[0].text


Related Topics



Leave a reply



Submit