使用JavaScript获取HTML标记中定义的原始标题 [英] Get raw title as defined in the HTML markup with JavaScript
问题描述
如果我的标题带有多个连续的空格,则 document.title
会为每个此类空格组合返回一个带有单个空格的字符串.
If I have a title with multiple consecutive spaces, document.title
returns a string with a single space for each such space combo.
示例:< title> []</title>
-HTML "[[]"
- document.title
Example:
<title>[ ]</title>
- HTML
"[ ]"
- document.title
另请参见下图.
问题-如何获取HTML文档中定义的原始字符串?这在我的一个抓取脚本中引起了一个错误,该错误的标题应该与其他元素匹配.
Question - how to get the raw string as it's defined in the HTML document? This caused a bug in one of my scraping scripts where a title should match some other element.
推荐答案
使用以下方法,我自己找到了答案:document.getElementsByTagName('title')[0].textContent
根据 Scott Marcus 的评论(这个答案),最好使用: document.querySelector("title").textContent
According to the comment of Scott Marcus (this answer), it's better to use:
document.querySelector("title").textContent
这篇关于使用JavaScript获取HTML标记中定义的原始标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!