Using DOM to get "description" meta tag.

Discussion in 'Web Design and Development' started by Nutter, Sep 25, 2008.

  1. Nutter macrumors 6502

    Joined:
    Mar 31, 2005
    Location:
    London, England
    #1
    Can anyone suggest a Javascript one-liner to get the description meta tag from a page's DOM?

    Doesn't need to work in anything but Safari...

    The best I've managed so far is as follows, but it seems to be case sensitive (in other words, doesn't work if the meta tag is named "Description", or "DESCRIPTION"):
    Code:
    document.getElementsByName('description')[0].content
     
  2. angelwatt Moderator emeritus

    angelwatt

    Joined:
    Aug 16, 2005
    Location:
    USA
    #2
    Your syntax is wrong, there's no HTML tags named description. You'd want to the tag name "meta." Can't do it as a one-liner unless you're 100% the description meta tag is first (or on some specific order). The following will grab the description meta tag though.

    JavaScript:
    PHP:
    var description;
    var 
    metas document.getElementsByTagName('meta');
    for (var 
    x=0,y=metas.lengthx<yx++) {
      if (
    metas[x].name.toLowerCase() == "description") {
        
    description metas[x];
      }
    }
    alert(description.content); // output content of description
     
  3. Nutter thread starter macrumors 6502

    Joined:
    Mar 31, 2005
    Location:
    London, England
  4. SrWebDeveloper macrumors 68000

    SrWebDeveloper

    Joined:
    Dec 7, 2007
    Location:
    Alexandria, VA, USA
    #4
    Expanding things a bit (just for fun)

    Just for fun, here's an expanded version of the excellent examples above (others beat me to it as usual!) which uses a function to pass any META name (real or invalid) and get back the content value:

    HTML:
    function GetMetaValue(meta_name) {
    
        var my_arr=document.getElementsByTagName("META");
        for (var counter=0; counter<my_arr.length; counter++) {
            if (my_arr[counter].name.toLowerCase() == meta_name.toLowerCase()) {
               return my_arr[counter].content;
               }
        }
        return "N/A";
    
    }
    
    document.write ("META Author is: "+GetMetaValue('author'));
    document.write ("<br />META Description is: "+GetMetaValue('description'));
    document.write ("<br />META invalid name is: "+GetMetaValue('foobar'));
    -jim

    ps: I use this in one of my sites CMS, just sharing useful code.
     

Share This Page