[英]Get contents of <h1> convert them it to text and set as a title of the page
I've got following structure of h1
element 我有以下h1
元素的结构
<h1>
<a href="#">My Text</a> <span>More Text</span> another text <a href="#">and a bit more</a>
</h1>
How can I get contents from such h1
and convert them to text so the output would be "My Text More Text another text and a bit more"
如何从这样的h1
获取内容并将它们转换为文本,因此输出将是"My Text More Text another text and a bit more"
and after that place it into the <title>
of the page? 然后把它放到页面的<title>
中? So no links, spans etc.. Just text? 所以没有链接,跨度等..只是文字?
使用jQuery它只是:
$('title').text($('h1').text());
Without jQuery, you can access the <h1>
's textContent
property ( innerText
in old IE), and you can change document.title
(like modifying the <title></title>
). 没有jQuery,你可以访问<h1>
的textContent
属性(旧IE中的innerText
),你可以更改document.title
(比如修改<title></title>
)。 Here's an example: 这是一个例子:
var text = "textContent" in document.body ? "textContent" : "innerText";
document.title = document.getElementsByTagName("h1")[0][text];
Depending on how you want to target the <h1>
, you can change the document.getElementsByTagName("h1")[0]
. 根据您希望如何定位<h1>
,您可以更改document.getElementsByTagName("h1")[0]
。
Also, I'm not sure how it affects the title
, but the whitespace before the first <a>
and after the last </a>
will be included unless you trim
the string. 另外,我不知道它是如何影响的title
,但第一前空格<a>
最后和后</a>
将被包括在内,除非你trim
的字符串。 So maybe turn it into: 所以也许把它变成:
function trim(s) {
if (typeof s === "string") {
s = s.replace(/^\s+|\s+$/g, "");
}
return s;
}
var el = document.getElementsByTagName("h1")[0],
text = "textContent" in el ? "textContent" : "innerText";
document.title = trim(el[text]);
DEMO: http://jsfiddle.net/tzGzC/ 演示: http : //jsfiddle.net/tzGzC/
Of course, with just jQuery, it's a lot simpler: 当然,只有jQuery,它更简单:
var el = $("h1").eq(0),
text = el.text();
document.title = $.trim(text);
DEMO: http://jsfiddle.net/kMXLW/ 演示: http : //jsfiddle.net/kMXLW/
References: 参考文献:
document.title
: https://developer.mozilla.org/en-US/docs/Web/API/document.title document.title
: https : //developer.mozilla.org/en-US/docs/Web/API/document.title .textContent
: https://developer.mozilla.org/en-US/docs/Web/API/Node.textContent .textContent
: https : //developer.mozilla.org/en-US/docs/Web/API/Node.textContent var h1content = document.getElementById("h1").innerHTML;
// stripped string taken from http://css-tricks.com/snippets/javascript/strip-html-tags-in-javascript/
var newTitle = h1content.replace(/(<([^>]+)>)/ig,"");
document.title = newTitle;
Something to note, crawlers do NOT follow Javascript code, meaning that although this will change the title of the page, it will not be Search Engine Optimized. 需要注意的是,抓取工具不遵循Javascript代码,这意味着虽然这会改变页面的标题,但它不会是搜索引擎优化的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.