I need this for SEO purposes. A small amount of pages on the website I’m working on, get generated dynamically, but their meta data is very generic – even though 5 of theses (different) pages have relatively different content, they will have the same title and description, which I’m trying to avoid.
I want to insert specific content from a page, into it’s meta tags via JavaScript.
The page looks something like this:
<html>
<head>
<title>This is the current title i want to replace</title>
<meta name="description" content="This is the current description i want to replace.">
</head>
<body>
<h1>Post Title</h1>
<div class="intro">
<p>Intro text goes here</p>
</div>
<div class="content">
<p>Content goes here</p>
<p>More content</p>
<p>Even more content</p>
</div>
</body>
</html>
I’m looking to inject the content of:
".intro" ("Intro text goes here" in this example) -> into the meta description of the page`
and
"h1" ("Post Title" in this example) -> into the meta title of the page
to make the end result look something like this:
<head>
<title>Post Title</title>
<meta name="description" content="Intro text goes here.">
</head>
As my JavaScript skills are limited, this is the only way i managed to change the page’s title and meta descritpion for now:
document.title = "Post Title";
document.getElementsByTagName('meta')["description"].content = "Intro text goes here.";
Obviously this is too static for the purpose, and doesn’t pull any data from the content of the page.
How do i amend the two lines of code above, in order for it to inject the desired strings into the meta title and description?
2
Answers
According to this, at least Google will spider your page with a headless browser that respects JS
Webmaster: does inserting meta elements into the head using js effect seo
Dynamic META tags in HTML5 and Javascript/jQuery
you can do this to change the description. It is however recommended to do all SEO preparations on the server
I’ll avoid commenting on best SEO practices (since the comments address this pretty well) and just address the code part of your question.
You just need to reference that
meta
element and adjust thecontent
attribute.