Home > Web Front-end > JS Tutorial > How to change the page title with javascript

How to change the page title with javascript

青灯夜游
Release: 2021-10-20 15:55:28
Original
2637 people have browsed it

Method: 1. Use "document.getElementsByTagName("title")[0].innerText = 'value'"; 2. Use "document.title='value'"; 3. Use "$( 'title').html('value')".

How to change the page title with javascript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

title is a special node element in HTML, because it can use document.getElementsByTagName("title")[0] to get the title tag of the web page, but it cannot use document.getElementsByTagName("title")[0].innerHtmlUse to change its value. After testing, there are two ways to modify native js, and it can also be easily set in jQuery. Let me introduce it to you below.

innerText method

Through console.log(document.getElementsByTagName("title")[0]), we found that < title> label, there are only text nodes in the label, so I guess it can only recognize TextNode, so I used innerText to set the value of title, and it succeeded.

document.getElementsByTagName("title")[0].innerText = &#39;需要设置的值&#39;;
Copy after login

document.title method

After testing, the value of title can also be set through document.title.

console.log(document.title);      # 可以获取title的值。
document.title = &#39;需要设置的值&#39;;    # 设置title的值。
Copy after login

Example

window.onfocus = function () {
 document.title = &#39;恢复正常了...&#39;;
};
window.onblur = function () {
 document.title = &#39;快回来~页面崩溃了&#39;;
};
Copy after login

We change the value of title when the browser gains focus and loses focus. You can find that the title changes when switching browser tabs.

jQuery method

Of course, if your project relies on jQuery, you can use the jq method to set the two methods in

$(&#39;title&#39;).html(&#39;值&#39;)

$(&#39;title&#39;).text(&#39;值&#39;)
Copy after login

jq All can be achieved

Summary

In native js we can use innerText, document.title To dynamically modify the title of the web page.

In jq, we can use $('title').html('value') or $('title') .text('value') to modify.

The above is the detailed method of changing browser TITLE with JS. If you find it useful, just bookmark it.

For more programming related knowledge, please visit: Programming Video! !

The above is the detailed content of How to change the page title with javascript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template