[英]How to get current html page title with javascript
I'm trying to get the plain html page title with javascript.我正在尝试使用 javascript 获取普通的 html 页面标题。
I use firefox and with我使用 firefox 和
document.title
I get extra "- Mozilla Firefox" to the end of the title.我在标题末尾添加了额外的“- Mozilla Firefox”。 I know it would be easy to get rid of this by modifying string but if they change text, use different format etc or some other browser modifies this differently I have extra text there again.
我知道通过修改字符串可以很容易地摆脱它,但是如果他们更改文本,使用不同的格式等或者其他浏览器以不同的方式修改它,我又会有额外的文本。
So, is there any cross browser way to get the plain tag content with javascript?那么,是否有任何跨浏览器的方式来获取 javascript 的纯标签内容? Jquery solution is ok.
Jquery解决就可以了。
One option from DOM directly: 直接来自DOM的一个选项:
$(document).find("title").text();
Tested only on chrome & IE9, but logically should work on all browsers. 仅在chrome和IE9上测试过,但逻辑上应该适用于所有浏览器。
Or more generic 或者更通用
var title = document.getElementsByTagName("title")[0].innerHTML;
试试这样
$('title').text();
Like this : 像这样 :
jQuery(document).ready(function () {
var title = jQuery(this).attr('title');
});
works for IE, Firefox and Chrome. 适用于IE,Firefox和Chrome。
$('title').text();
returns all the title 返回所有标题
but if you just want the page title then use 但如果您只是想要页面标题,那么请使用
document.title
You can get it with plain JavaScript DOM methods.The concept is easy:您可以使用普通的 JavaScript DOM 方法获得它。这个概念很简单:
Retrieve title
element from DOM.从 DOM 中检索
title
元素。
Get its content using innerHTML
or innerText
.使用
innerHTML
或innerText
获取其内容。
So:所以:
const titleElement = document.getElementsByTagName("title")
const title = titleElement.innerText
console.log(title) // The title of the HTML page.
To retrieve, you can use other methods such as querySelector
, or adding an id to title, getElementById
.要检索,您可以使用其他方法,例如
querySelector
,或为标题添加 id, getElementById
。
To get title and save it to a constant use:要获取标题并将其保存为常量使用:
const { title } = document;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.