I need this for SEO optimization. The website I'm working on has a small set of pages that are dynamically generated, but their metadata is very generic - even though these 5 (different) pages have relatively different content, their titles and descriptions are the same, which I want Avoid this situation.
I want to insert the content of a specific page into its meta tag via JavaScript.
The structure of the page is as follows:
<html> <head> <title>这是我想要替换的当前标题</title> <meta name="description" content="这是我想要替换的当前描述。"> </head> <body> <h1>文章标题</h1> <div class="intro"> <p>这里是简介文本</p> </div> <div class="content"> <p>这里是内容</p> <p>更多内容</p> <p>还有更多内容</p> </div> </body> </html>
I want to inject the following:
".intro" (in this case "Intro text here") -> to the meta description of the page
and
"h1" (in this case "post title") -> to the meta title of the page
Make the final result look like this:
<head> <title>文章标题</title> <meta name="description" content="这里是简介文本。"> </head>
Due to my limited JavaScript skills, currently I can only change the page's title and meta description via:
document.title = "文章标题"; document.getElementsByTagName('meta')["description"].content = "这里是简介文本。";
Obviously, this method is too static and cannot obtain any data from the page content.
How can I modify the above two lines of code so that the required strings are injected into the meta title and description?
I will avoid commenting on best SEO practices (as the comments already address this well) and only answer the code portion of your question.
You just need to reference that
meta
element and adjust thecontent
attribute.