Set description meta tag

Alex Ritter picture Alex Ritter · Oct 27, 2012 · Viewed 10.6k times · Source

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?

Answer

D. Strout picture D. Strout · Oct 27, 2012

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?