Set description meta tag

11,092

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?

Share:
11,092
Alex Ritter
Author by

Alex Ritter

Updated on September 12, 2022

Comments

  • Alex Ritter
    Alex Ritter almost 2 years

    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?

  • Alex Ritter
    Alex Ritter over 11 years
    You are right. I know it's not the proper way to add a title tag, but unfortunately for me, the pages are generated dynamically using asp.net, and while the module generating the pages does support adding html content, and url keywords, it does not support adding meta tags.
  • Alex Ritter
    Alex Ritter over 11 years
    After doing some research, I found this blog post ifinity.com.au/2012/10/04/… Anything in the title tag is better than nothing, right?