如何使用 javascript 更改 <title> 元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4175750/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 10:36:04  来源:igfitidea点击:

How do you change the <title> element with javascript?

javascripthtmltitle

提问by chromedude

I have a HTML <title>element which I want to dynamically change depending on other elements. I tried using document.getElementsByTagName('title').innerHTML = dynamicContentbut this did not seem to work. I have seen it done before, but I can't seem to figure out exactly how to do this.

我有一个 HTML<title>元素,我想根据其他元素动态更改它。我尝试使用,document.getElementsByTagName('title').innerHTML = dynamicContent但这似乎不起作用。我以前看过它,但我似乎无法确切地弄清楚如何做到这一点。

回答by Tomas Petricek

Do you mean the <title>element in <head>of the page?
If yes, then changing document.titleshould do the trick.

你的意思是页面中的<title>元素<head>
如果是,那么改变document.title应该可以解决问题。

回答by AndreKR

getElementsByTagName()returns a NodeList, so you need to pick one element:

getElementsByTagName()返回一个 NodeList,因此您需要选择一个元素:

document.getElementsByTagName('title')[0].innerHTML = dynamicContent

There's also a shortcut to the title:

标题还有一个快捷方式:

document.title = dynamicContent

回答by meder omuraliev

You can manipulate

你可以操纵

a) document.title = 'blah';

a) document.title = 'blah';

b) .textContent or .innerText depending on the browser

b) .textContent 或 .innerText 取决于浏览器