PDA

View Full Version : Using DOM to get "description" meta tag.




Nutter
Sep 25, 2008, 03:50 PM
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"):
document.getElementsByName('description')[0].content



angelwatt
Sep 25, 2008, 04:58 PM
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:
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

Nutter
Sep 25, 2008, 08:07 PM
Thanks!

SrWebDeveloper
Sep 26, 2008, 10:58 AM
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:

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.