获取 title 元素的内容
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>My Title</title>
</head>
<body>
<script type="text/javascript">
window.onload = function(event) {
console.log(event)
main()
}
function main() {
// 方法一
console.log(document.title)
// 方法二
const title = document.querySelector("title")
console.log(title.innerText)
}
</script>
</body>
</html>
修改 title 元素的内容
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>My Title</title>
</head>
<body>
<script type="text/javascript">
window.onload = function(event) {
// console.log(event);
main();
}
function main() {
window.setInterval(updateTitle, 1000);
}
function updateTitle() {
const now = new Date();
console.log(now.toLocaleString());
// 方法一
document.title = now.toLocaleString("zh-CN");
// // 方法二
// const title = document.querySelector("title");
// title.innerText = now.toLocaleString("zh-CN");
}
</script>
</body>
</html>
参考
Web technology for developers > Web APIs > HTMLTitleElement
Web technology for developers > Web APIs > HTMLElement > HTMLElement.innerText