Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

Nutter

macrumors 6502
Original poster
Mar 31, 2005
432
0
London, England
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
 
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.length; x<y; x++) {
  if (metas[x].name.toLowerCase() == "description") {
    description = metas[x];
  }
}
alert(description.content); // output content of description
 
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.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.