使用Javascript从h1标签动态更改页面标题 [英] Dynamically change page title from h1 tag using Javascript

查看:447
本文介绍了使用Javascript从h1标签动态更改页面标题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,感谢您抽出宝贵时间阅读此问题.很棒的社区Stack Overflow有:)

First off, thanks for taking the time to read this question. What a great community Stack Overflow has :)

我需要基于页面的h1元素中包含的文本来更改页面的标题标签.

I need to change the title tag of a page based on the text contained in the h1 element on that page.

我一直在搜索,并且找到了Javascript函数"document.title".我一直在尝试,尝试从具有"Category-H1"类的h1元素中提取文本.

I've been searching around, and I have found the "document.title" Javascript function. I've been playing around with it, trying to pull the text from my h1 element that has the class of "Category-H1".

<script type="text/javascript">
    document.title = document.getElementsByClassName("Category-H1");
</script>

但是,它只是将页面标题设置为"[object HTMLCollection]",据我所知这是一个空值. JS最好的办法就是这样做吗?我知道我的代码受了限制,有什么提示吗?

However, it is just setting the page title to "[object HTMLCollection]", which as I understand is a null value. Is JS the best was to do this? I know my code is jacked, any tips?

提前谢谢! -亚历克斯

Thanks in advance! - Alex

修改

我被告知,代码行返回的是集合对象,而不是字符串.有人指出了一个代码示例:

I have been informed that line of code returns a collection object and not a string. It was pointed to a code example of:

setTimeout(function () { document.title = "iFinity User Profile - " + document.getElementById("test").outerText; }, 1000); 

但是,此代码产生的页面标题为"iFinity用户配置文件-未定义".我在该页面上将h1元素设置为"test"的ID.

However, this code produces a page title of "iFinity User Profile - undefined". I have the h1 element on that page set to the id of "test".

推荐答案

您快到了.

[object HTMLCollection]不是空值-它是html元素集合的字符串表示形式.您要选择第一个,然后从中获取内部html.

[object HTMLCollection] is not a null value--it is the string representation of a collection of html elements. You want to choose the first one and then get the inner html from it.

document.getElementsByClassName("Category-H1")[0].innerHTML

此外,请确保在文档加载后执行此操作.您可以通过在文档末尾添加脚本来执行此操作,也可以使其在正文的onload事件上运行.

Also, make sure you do this after the document has loaded. You can either do this by adding the script at the end of your document, or have it run on the onload event of the body.

这篇关于使用Javascript从h1标签动态更改页面标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆