How to insert specific string into page meta tag using JavaScript
P粉904191507
P粉904191507 2023-09-16 20:17:07
0
1
711

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?

P粉904191507
P粉904191507

reply all(1)
P粉214089349

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>文章标题</title>
    <meta name="description" content="这里是简介文字。">
  </head>
  <body>
  
    <!-- 将这个<script>标签放在闭合的body标签之前,
         这样它会在所有页面HTML解析完之后运行。 -->
    <script>
      // 获取对meta元素的引用:
      const meta = document.querySelector("meta[name='description']");
      
      console.log(meta);  // 用于测试
      meta.content = "新的内容";  // 将其设置为你需要的任何值。
      console.log(meta);  // 用于测试      
    </script>
  </body>
</html>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template