Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - quickest way to extract document meta fields

I need to extract the document's "description" meta tag.

The default way would be to use document.getElementsByTagName('META') and then iterate through the array - as found in: http://www.rgagnon.com/jsdetails/js-0070.html

But I'm wondering if there's no other quicker, "one line of code" approach. I'm not familiar with xPath - but maybe that could work? Any ideas?


1 Answers

sure...

var desc = document.getElementsByName('description')[0].getAttribute('content');

This presumes that there is a Meta Tag named description of course.

To be more complete, this would catch the description regardless of case.

function getDesc(){
  var metas = document.getElementsByTagName('meta');
  for(var i=0;mLen=metas.length;i<mLen;i++){
    if(metas[i].getAttribute('name').toLowerCase() == 'description'){
      return metas[i].getAttribute('content');
    }
  }
  return null;//or empty string if you prefer
}
var desc = getDesc();
like image 56
scunliffe Avatar answered Apr 22 '26 00:04

scunliffe