JavaScript 获取 <title> 元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21223382/
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-27 20:25:24  来源:igfitidea点击:

JavaScript get the <title> element

javascripthtmlgetelementsbytagname

提问by Progo

I am writing a script that will make the title tag switch messages every few seconds.

我正在编写一个脚本,该脚本将使标题标签每隔几秒钟切换一次消息。

I wrote the code but when I tried to run it, I got an error here:

我写了代码,但是当我尝试运行它时,我在这里遇到错误:

title = document.getElementByTagName("title")

The error I am getting says: TypeError: 'undefined' is not a function (evaluating 'document.getElementByTagName("title")').

我得到的错误说:TypeError: 'undefined' is not a function (evaluating 'document.getElementByTagName("title")')

The scripttag is below the titletag and inside my script tag I have this to make sure the page has fully loaded before the code is ran:

script标签位于标签下方title,在我的脚本标签内,我使用它来确保在运行代码之前页面已完全加载:

window.addEventListener("DOMContentLoaded", function(){
    //code

Why am I getting an error when I try to get the titletag?

为什么我在尝试获取title标签时会收到错误消息?

Thank you.

谢谢你。

回答by Quentin

getElementByTagNameisn't a function (unless you write one).

getElementByTagName不是一个函数(除非你写一个)。

There is a getElementsByTagNamefunction (note Elements is plural) which returns a node list.

有一个返回节点列表的getElementsByTagName函数(注意 Elements 是复数)。

It's usually simpler to just use document.titlethough (which is a string).

虽然通常使用更简单document.title(这是一个字符串)。

回答by Schien

If you're looking into changing the title of the document, which is in the markup, use:

如果您正在考虑更改标记中的文档标题,请使用:

document.title = 'New Title';

Your code works with some correction, and it works in a more general case:

您的代码可以进行一些更正,并且可以在更一般的情况下使用:

document.getElementsByTagName('title')[0]='New Title';

However, it doesn't really change the document title, like the first solution.

但是,它并没有真正改变文档标题,就像第一个解决方案一样。

回答by Lewis Goddard

document.titlestores the title by default, and unless you are running JavaScript on HTML that isn't from the current page, it is usually simplest to just use that.

document.title默认情况下存储标题,除非您在不是来自当前页面的 HTML 上运行 JavaScript,否则使用它通常是最简单的。

However, the code you wanted to write in bare JavaScript was:
document.getElementsByTagName('title')[0].innerHTML;

但是,您想用纯 JavaScript 编写的代码是:
document.getElementsByTagName('title')[0].innerHTML;

If you are already using jQuery, you can use $(document).find('title').text();to set your own variable.

如果您已经在使用 jQuery,您可以使用$(document).find('title').text();来设置您自己的变量。