How to retrieve Meta tags via Javascript?

adworldmedia
adworldmedia used Ask the Experts™
on
I need to extract the META keyword contents via Javascript, and I'm having issues.  The code I'm using doesn't seem to work.

Any help would be appreciated.

function getMetaKeywords() {
    var keywords = '';
    var metas = document.getElementsByTagName('meta');
    if (metas) {
        for (var x=0,y=metas.length; x<y; x++) {
            if (metas[x].name.toLowerCase() == "keywords") {
                keywords += metas[x].content;
            }
        }
    }
    return keywords != '' ? keywords : false;
}

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Fixer of Problems
Most Valuable Expert 2014
Commented:
The code on this page http://forums.macrumors.com/showthread.php?t=569947 works.  A modified example:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
 "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<title>JS-Meta</title>
<meta name="description" content="Descript" />
<meta name="keywords" content="Keywordssss" />
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
</head>
<body>
<h1>JS-Meta</h1>
<script type="text/javascript">
<!--
var description;
var metas = document.getElementsByTagName('meta');
for (var x=0,y=metas.length; x<y; x++) {
	document.write(metas[x].name+"<br>");
  if (metas[x].name.toLowerCase() == "description") {
    description = metas[x];
  }
}
alert(description.content); // output content of description  
// -->
</script>
</body>
</html>

Open in new window

here is a simple jquery one liner to do the same:-
var metaContent = $('meta').attr("content");
var metaName = $('meta').attr('name');

Open in new window

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial