Alex Ritter
Alex Ritter

Reputation: 1041

Set description meta tag

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

Answers (3)

Ashley Strout
Ashley Strout

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!


*Frankly, I don't speak from experience here, just common sense. It really doesn't make sense for meta information to be dynamic, so even if a spider was smart enough to run JavaScript, why would it recheck meta information after doing so?

Upvotes: 6

Chris Miller
Chris Miller

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

Elliot Bonneville
Elliot Bonneville

Reputation: 53291

You can use the getAttribute() function to do this:

document.title = document.getElementsByClassName("Category-H1")[0].getAttribute("yourDescriptionMetaTag");

Upvotes: 0

Related Questions