简体   繁体   English

你怎么改变 <title>用javascript的元素?

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

I have a HTML <title> element which I want to dynamically change depending on other elements. 我有一个HTML <title>元素,我想根据其他元素动态更改。 I tried using document.getElementsByTagName('title').innerHTML = dynamicContent but this did not seem to work. 我尝试使用document.getElementsByTagName('title').innerHTML = dynamicContent但这似乎不起作用。 I have seen it done before, but I can't seem to figure out exactly how to do this. 我以前看过它,但我似乎无法弄明白该怎么做。

Do you mean the <title> element in <head> of the page? 你的意思是页面<head>中的<title>元素吗?
If yes, then changing document.title should do the trick. 如果是,那么改变document.title就可以了。

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

You can manipulate 你可以操纵

a) document.title = 'blah'; a)document.title ='blah';

b) .textContent or .innerText depending on the browser b).textContent或.innerText取决于浏览器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM