Reputation: 1041
I have recently added the following line of Javascript code to a few pages on my site, in order to pull the title tag from the H1 element with the CSS class of "Category-H1".
document.title = document.getElementsByClassName("Category-H1")[0].innerHTML;
I am curious, can I do something similar to pull in the description tag using JS from my H2 element?
Upvotes: 2
Views: 12399
Reputation: 6258
This is doable, but I'm not sure if it would accomplish what you're hoping for. Most people use meta description tags for SEO purposes, but many (most?) search engines won't recognize the description if it is set by JavaScript after the page loads*. Still, if you want to do this:
var meta=document.getElementsByTagName("meta");
for (var i=0; i<meta.length; i++) {
if (meta[i].name.toLowerCase()=="description") {
meta[i].content=document.getElementsByClassName("Category-H1")[0].innerHTML;
}
}
Hope this helps!
Upvotes: 6
Reputation: 493
I don't think this is going to be good for SEO. While it may work, I don't think spiders are expecting these tags to be dynamic. But if SEO isn't the point, here's another answer that shows how with jquery.
Javascript To Change Metadata / Metatags Dynamically
Upvotes: -1
Reputation: 53291
You can use the getAttribute()
function to do this:
document.title = document.getElementsByClassName("Category-H1")[0].getAttribute("yourDescriptionMetaTag");
Upvotes: 0