通过JS动态设置网页中H1标签中的内容为title标题

JavaScript013

通过JS动态设置网页中H1标签中的内容为title标题,第1张

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

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

但是,它只是将页面标题设置为“ [object HTMLCollection]”,据我所知这是一个空值。

正确来说[object HTMLCollection]不是空值-它是html元素集合的字符串表示形式,可以从中获取需要的值。

思路:使用document.title获取页面标题,使用value属性为文本框赋值,关键代码:

document.getElementById(input_id).value=document.title

实例演示如下:

1、HTML结构

<html>

<head>

    <title>TEST</title>

</head>

<body>

    <input type="text" id="test"/>

    <input type='button' value='点击按钮获取页面标题' onclick="fun()"/>

</body>

2、javascript代码

function fun(){

var title = document.title

document.getElementById("test").value = title

}

3、效果演示

参考下面代码

<body onload="init()">

<script type="text/javascript">

function init(){

//拿到标题栏的文本

var title = document.title

//将文本字符串转换为数组

var arr = title.split("")

//拿到数组的第一个元素,并从数组中删除

var first = arr.shift()

//将第一个元素添加到数组的最后

arr.push(first)

//将数组再组合成一个字符串

title = arr.join("")

document.title = title

//每隔一秒做一遍前6步

setTimeout("init()",1000)

}

</script>

</body>