How do I get the information from a meta tag with JavaScript?

JavascriptHtmlGreasemonkeyMeta Tags

Javascript Problem Overview


The information I need is in a meta tag. How can I access the "content" data of the meta tag when property="video"?

HTML:

<meta property="video" content="http://video.com/video33353.mp4" />

Javascript Solutions


Solution 1 - Javascript

The other answers should probably do the trick, but this one is simpler and does not require jQuery:

document.head.querySelector("[property~=video][content]").content;

The original question used an RDFa tag with a property="" attribute. For the normal HTML <meta name="" …> tags you could use something like:

document.querySelector('meta[name="description"]').content

Solution 2 - Javascript

You can use this:

function getMeta(metaName) {
  const metas = document.getElementsByTagName('meta');

  for (let i = 0; i < metas.length; i++) {
    if (metas[i].getAttribute('name') === metaName) {
      return metas[i].getAttribute('content');
    }
  }

  return '';
}

console.log(getMeta('video'));

Solution 3 - Javascript

One liner here

document.querySelector("meta[property='og:image']").getAttribute("content");

Solution 4 - Javascript

There is an easier way:

document.getElementsByName('name of metatag')[0].getAttribute('content')

Solution 5 - Javascript

function getMetaContentByName(name,content){
   var content = (content==null)?'content':content;
   return document.querySelector("meta[name='"+name+"']").getAttribute(content);
}

Used in this way:

getMetaContentByName("video");

The example on this page:

getMetaContentByName("twitter:domain");

Solution 6 - Javascript

If you use JQuery, you can use:

$("meta[property='video']").attr('content');

Solution 7 - Javascript

In Jquery you can achieve this with:

$("meta[property='video']");

In JavaScript you can achieve this with:

document.getElementsByTagName('meta').item(property='video');

Solution 8 - Javascript

document.querySelector('meta[name=NAME_OF_THE_FIELD]').content

this way you can get the content of the meta.

Solution 9 - Javascript

Way - [ 1 ]

function getMetaContent(property, name){
	return document.head.querySelector("["+property+"="+name+"]").content;
}
console.log(getMetaContent('name', 'csrf-token'));

You may get error: Uncaught TypeError: Cannot read property 'getAttribute' of null


Way - [ 2 ]

function getMetaContent(name){
	return document.getElementsByTagName('meta')[name].getAttribute("content");
}
console.log(getMetaContent('csrf-token'));

You may get error: Uncaught TypeError: Cannot read property 'getAttribute' of null


Way - [ 3 ]

function getMetaContent(name){
	name = document.getElementsByTagName('meta')[name];
	if(name != undefined){
		name = name.getAttribute("content");
		if(name != undefined){
			return name;
		}
	}
    return null;
}
console.log(getMetaContent('csrf-token'));

Instead getting error, you get null, that is good.

Solution 10 - Javascript

Simple one, right?

document.head.querySelector("meta[property=video]").content

Solution 11 - Javascript

This code works for me

<meta name="text" property="text" content="This is text" />
<meta name="video" property="text" content="http://video.com/video33353.mp4" />

JS

var x = document.getElementsByTagName("META");
    var txt = "";
    var i;
    for (i = 0; i < x.length; i++) {
        if (x[i].name=="video")
        {
             alert(x[i].content);
         }
        
    }    
    

Example fiddle: http://jsfiddle.net/muthupandiant/ogfLwdwt/

Solution 12 - Javascript

function getDescription() {
    var info = document.getElementsByTagName('meta');
    return [].filter.call(info, function (val) {
        if(val.name === 'description') return val;
    })[0].content;
}

update version:

function getDesc() {
    var desc = document.head.querySelector('meta[name=description]');
    return desc ? desc.content : undefined;
}

Solution 13 - Javascript

My variant of the function:

const getMetaValue = (name) => {
  const element = document.querySelector(`meta[name="${name}"]`)
  return element?.getAttribute('content')
}

Solution 14 - Javascript

copy all meta values to a cache-object:

/* <meta name="video" content="some-video"> */

const meta = Array.from(document.querySelectorAll('meta[name]')).reduce((acc, meta) => (
  Object.assign(acc, { [meta.name]: meta.content })), {});

console.log(meta.video);

Solution 15 - Javascript

Here's a function that will return the content of any meta tag and will memoize the result, avoiding unnecessary querying of the DOM.

var getMetaContent = (function(){
        var metas = {};
        var metaGetter = function(metaName){
            var theMetaContent, wasDOMQueried = true;;
            if (metas[metaName]) {
                theMetaContent = metas[metaName];
                wasDOMQueried = false;
            }
            else {
                 Array.prototype.forEach.call(document.getElementsByTagName("meta"), function(el) {
                    if (el.name === metaName) theMetaContent = el.content;
                    metas[metaName] = theMetaContent;
                });
            }
            console.log("Q:wasDOMQueried? A:" + wasDOMQueried);
            return theMetaContent;
        }
        return metaGetter;
    })();

getMetaContent("description"); /* getMetaContent console.logs the content of the description metatag. If invoked a second time it confirms that the DOM  was only queried once */

And here's an extended version that also queries for open graph tags, and uses Array#some:

var getMetaContent = (function(){
        var metas = {};
        var metaGetter = function(metaName){
            wasDOMQueried = true;
            if (metas[metaName]) {
                wasDOMQueried = false;
            }
            else {
                 Array.prototype.some.call(document.getElementsByTagName("meta"), function(el) {
                        if(el.name === metaName){
                           metas[metaName] = el.content;
                           return true;
                        }
                        if(el.getAttribute("property") === metaName){
                           metas[metaName] = el.content;
                           return true;
                        }
                        else{
                          metas[metaName] = "meta tag not found";
                        }  
                    });
            }
            console.info("Q:wasDOMQueried? A:" + wasDOMQueried);
            console.info(metas);
            return metas[metaName];
        }
        return metaGetter;
    })();

getMetaContent("video"); // "http://video.com/video33353.mp4"

Solution 16 - Javascript

If you are interessted in a more far-reaching solution to get all meta tags you could use this piece of code

function getAllMetas() {
    var metas = document.getElementsByTagName('meta');
    var summary = [];
    Array.from(metas)
        .forEach((meta) => {
            var tempsum = {};
            var attributes = meta.getAttributeNames();
            attributes.forEach(function(attribute) {
                tempsum[attribute] = meta.getAttribute(attribute);
            });
            summary.push(tempsum);
        });
    return summary;
}

// usage
console.log(getAllMetas());

Solution 17 - Javascript

The simple way preferred

We can use direct one line to get meta description or keyword or any meta tag in head section as this code:

document.head.getElementsByTagName('meta')['description'].getAttribute('content');

Just change ['description'] to keywords or element of meta name rang

This is an example: using document.head to get meta names values

Solution 18 - Javascript

I personally prefer to just get them in one object hash, then I can access them anywhere. This could easily be set to an injectable variable and then everything could have it and it only grabbed once.

By wrapping the function this can also be done as a one liner.

var meta = (function () {
    var m = document.querySelectorAll("meta"), r = {};
    for (var i = 0; i < m.length; i += 1) {
        r[m[i].getAttribute("name")] = m[i].getAttribute("content")
    }
    return r;
})();

Solution 19 - Javascript

FYI according to https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta global attributes are valid which means the id attribute can be used with getElementById.

Solution 20 - Javascript

Using meta root and then getting and setting any of its properties:

let meta = document.getElementsByTagName('meta')

console.log(meta.video.content)
> "http://video.com/video33353.mp4"

meta.video.content = "https://www.example.com/newlink"

Solution 21 - Javascript

<html>
<head>
<meta property="video" content="http://video.com/video33353.mp4" />
<meta name="video" content="http://video.com/video33353.mp4" />
</head>
<body>

<script>
var meta = document.getElementsByTagName("meta");
    size = meta.length;

for(var i=0; i<size; i++) {
    if (meta[i].getAttribute("property") === "video") {
        alert(meta[i].getAttribute("content"));
    }
}
meta = document.getElementsByTagName("meta")["video"].getAttribute("content");
alert(meta);
</script>
</body>
</html>

Demo

Solution 22 - Javascript

document.head.querySelector('meta[property=video]').content;

Solution 23 - Javascript

if the meta tag is:

<meta name="url" content="www.google.com" />

JQuery will be:

const url = $('meta[name="url"]').attr('content'); // url = 'www.google.com'

JavaScript will be: (It will return whole HTML)

const metaHtml = document.getElementsByTagName('meta').url // metaHtml = '<meta name="url" content="www.google.com" />'

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsupercoolvilleView Question on Stackoverflow
Solution 1 - JavascriptjoepioView Answer on Stackoverflow
Solution 2 - JavascriptSaketView Answer on Stackoverflow
Solution 3 - JavascriptCedView Answer on Stackoverflow
Solution 4 - JavascriptmuchachoView Answer on Stackoverflow
Solution 5 - JavascriptdevMariuszView Answer on Stackoverflow
Solution 6 - JavascriptElise ChantView Answer on Stackoverflow
Solution 7 - JavascriptPrameet JainView Answer on Stackoverflow
Solution 8 - JavascriptAhmed BenhajarView Answer on Stackoverflow
Solution 9 - Javascript Юрий СветловView Answer on Stackoverflow
Solution 10 - JavascriptErik CampobadalView Answer on Stackoverflow
Solution 11 - JavascriptmuTheTechieView Answer on Stackoverflow
Solution 12 - JavascriptVanillaView Answer on Stackoverflow
Solution 13 - JavascriptAleh AtsmanView Answer on Stackoverflow
Solution 14 - JavascriptMila NautikusView Answer on Stackoverflow
Solution 15 - JavascriptcssimsekView Answer on Stackoverflow
Solution 16 - JavascriptSchabbiView Answer on Stackoverflow
Solution 17 - JavascriptWesam NafaaView Answer on Stackoverflow
Solution 18 - JavascriptWes JonesView Answer on Stackoverflow
Solution 19 - JavascriptjmozView Answer on Stackoverflow
Solution 20 - Javascriptassayag.orgView Answer on Stackoverflow
Solution 21 - JavascriptRenexoView Answer on Stackoverflow
Solution 22 - Javascriptparthiban dhanapalView Answer on Stackoverflow
Solution 23 - JavascriptS K RView Answer on Stackoverflow