{

How to get the title of an HTML webpage in javascript?


javascript html title example

In this tutorial, learn how to get the current web HTML page title in javascript.

And also how to update the page title with value in javascript.

On the Html page, the Title tag contains the text content of a complete web page. The <title> tag in HTML contains text content.

Here is a title example in HTML

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title> Hello World title</title>
</head>

<body>
    This is a simple web HTML page
</body>

</html>

how to get the Current page title in javascript?

There are several ways to get the current page title in javascript.

First, an easy way is using document.title.

console.log(document.title)

Second, using dom getElementsByTagName API getElementsByTagName('title') returns an array of elements, get the first element.

The textContent property on the HTML element returns the title of a page.

you can also use innerHTML to get the title. textContent is recommended to get the title.

var titleElement = document.getElementsByTagName("title")[0];
console.log(titleElement) //<title> Hello World title</title>

console.log(titleElement.textContent) //Hello World title
console.log(titleElement.innerHTML) //Hello World title
  • get the title using jquery Selector syntax.

First, Select a document using HTML element selector syntax. Filter the DOM elements with a title tag and return the title HTML element Finally, call text() method to get text content.

var titleText = $(html).filter('title').text();
console.log(titleText) //Hello World title

or you can try

$('head > title').text();

How to change the title of the webpage using javascript and jquery

There are multiple ways, we can change the title.

  • using the document object, change the title attribute with a new value
document.title = 'New HTML title value';
  • Another using getElementsByTagName

First, get an element using getElementsByTagName and change the title directly

document.getElementsByTagName('title')[0]='New HTML title value content';
  • jquery to change the title Select an HTML element and find the title and update the title using text() method
$(html).find('title').text('new html title value using jquery');
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.