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>這是我想要替換的當(dāng)前標(biāo)題</title> <meta name="description" content="這是我想要替換的當(dāng)前描述。"> </head> <body> <h1>文章標(biāo)題</h1> <div class="intro"> <p>這里是簡(jiǎn)介文本</p> </div> <div class="content"> <p>這里是內(nèi)容</p> <p>更多內(nèi)容</p> <p>還有更多內(nèi)容</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>文章標(biāo)題</title> <meta name="description" content="這里是簡(jiǎn)介文本。"> </head>
Due to my limited JavaScript skills, currently I can only change the page's title and meta description via:
document.title = "文章標(biāo)題"; document.getElementsByTagName('meta')["description"].content = "這里是簡(jiǎn)介文本。";
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 the content
attribute.
<!doctype html> <html> <head> <title>文章標(biāo)題</title> <meta name="description" content="這里是簡(jiǎn)介文字。"> </head> <body> <!-- 將這個(gè)<script>標(biāo)簽放在閉合的body標(biāo)簽之前, 這樣它會(huì)在所有頁(yè)面HTML解析完之后運(yùn)行。 --> <script> // 獲取對(duì)meta元素的引用: const meta = document.querySelector("meta[name='description']"); console.log(meta); // 用于測(cè)試 meta.content = "新的內(nèi)容"; // 將其設(shè)置為你需要的任何值。 console.log(meta); // 用于測(cè)試 </script> </body> </html>