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

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" />

This question is related to javascript html greasemonkey meta-tags

The answer is


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());

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"

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.


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);

There is an easier way:

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

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.


In Jquery you can achieve this with:

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

In JavaScript you can achieve this with:

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

<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


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" />'

One liner here

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

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");

Simple one, right?

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

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/


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

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;
}

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;
})();

My variant of the function:

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

If you use JQuery, you can use:

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

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to greasemonkey

window.close and self.close do not close the window in Chrome Why doesn't document.addEventListener('load', function) work in a greasemonkey script? How do I get the information from a meta tag with JavaScript? Event when window.location.href changes alert a variable value Get image data url in JavaScript? How can I use jQuery in Greasemonkey?

Examples related to meta-tags

Showing Thumbnail for link in WhatsApp || og:image meta-tag doesn't work What is initial scale, user-scalable, minimum-scale, maximum-scale attribute in meta tag? Is it still valid to use IE=edge,chrome=1? Provide an image for WhatsApp link sharing How to add meta tag in JavaScript How do I get the information from a meta tag with JavaScript? What is the attribute property="og:title" inside meta tag? What's the point of 'meta viewport user-scalable=no' in the Google Maps API <meta charset="utf-8"> vs <meta http-equiv="Content-Type"> HTML meta tag for content language