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

25

244

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" />
Raptor answered 23/9, 2011 at 5:20 Comment(1)
Note that <meta> is supposed to have a name attribute, not property. Developers using the standard attribute will need to adapt the code given by most answers.Sulfonal
P
159

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'));
Peccadillo answered 23/9, 2011 at 5:25 Comment(6)
What you really want is 'let' to keep them locally defined ;)Dolorisdolorita
If you can use querySelector, you can do something like this: document.querySelector("meta[property='og:url']").getAttribute('content')Sangsanger
I think this answer is not more relevant and you should really use #7525085Cheat
Skip this answer. It doesn't work in the OP's [admittedly odd] case since it looks at the "name" rather than "property" attribute. And in its current state it's overly complex but without any backwards compatibility advantage — any browsers that support const/let should support .querySelector!Crystallo
for just one meta attribute, why to loop over multiple times ? it may have hundreds of meta tags or it may need to get the meta value multiple times.Sportswoman
why would someone loop through all metas everytime ? if there are hundreds, what about the performance ?Sportswoman
V
372

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
Vinegar answered 26/2, 2016 at 10:20 Comment(5)
Even though my meta is in the <head> tag, document.head.querySelector gave me null but document.querySelector worked perfectlyOocyte
To get it working with OG tags add quotes to it like this_: var title = document.head.querySelector('[property="og:title"]');Lionellionello
NIce. Which purpose does the part "[content]" serve? Without it, I also get the meta element.Knives
@Knives It does seem somewhat superfluous. The snippet will always throw a TypeError if the tag is not found by its "property". Including [content] in the selector extends that exception to the case where any matching tag lacks a content attribute. IMO it makes more sense in that case to get a null result but it's up to the implementer's preference I guess.Crystallo
document.querySelector or document.querySelectorAll does not work when unclosed element does not end with /, for example on this site, meta tag viewport <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0, minimum-scale=1.0"> is without / and document.querySelector(meta[property='viewport']) returns null.Pylos
P
159

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'));
Peccadillo answered 23/9, 2011 at 5:25 Comment(6)
What you really want is 'let' to keep them locally defined ;)Dolorisdolorita
If you can use querySelector, you can do something like this: document.querySelector("meta[property='og:url']").getAttribute('content')Sangsanger
I think this answer is not more relevant and you should really use #7525085Cheat
Skip this answer. It doesn't work in the OP's [admittedly odd] case since it looks at the "name" rather than "property" attribute. And in its current state it's overly complex but without any backwards compatibility advantage — any browsers that support const/let should support .querySelector!Crystallo
for just one meta attribute, why to loop over multiple times ? it may have hundreds of meta tags or it may need to get the meta value multiple times.Sportswoman
why would someone loop through all metas everytime ? if there are hundreds, what about the performance ?Sportswoman
R
134

One liner here

document.querySelector("meta[property='og:image']").getAttribute("content");
Radie answered 12/10, 2016 at 15:29 Comment(0)
A
31

There is an easier way:

document.getElementsByName('name of metatag')[0].getAttribute('content')
Aleasealeatory answered 30/5, 2016 at 18:19 Comment(3)
This works back to at least IE11, which makes it more useful.Berner
The document.querySelector version works all the way to IE8, so it's plentyNapoleon
This is a pretty good way normally, but note that the OP is using the RDFa "property" attribute instead of the more basic "name" attribute (#22350605)Crystallo
M
21
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");
Megargee answered 15/2, 2014 at 14:44 Comment(2)
I used this tidbit, but on a certain page was getting a type error as undefined because the meta tag itself was missing. I resolved that by assigning a variable and wrapping the document.queryselector in a try statement so I could get "" by default in case of error.Alfeus
function getMetaContentByName(name,content){ var content = (content==null)?'content':content; try{ return document.querySelector("meta[name='"+name+"']").getAttribute(content); }catch{ return null; } }Megargee
A
17

If you use JQuery, you can use:

$("meta[property='video']").attr('content');
Apophyge answered 30/12, 2013 at 3:36 Comment(1)
Assuming jquery, or some library; not javascriptHippomenes
C
16

In Jquery you can achieve this with:

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

In JavaScript you can achieve this with:

document.getElementsByTagName('meta').item(property='video');
Changsha answered 29/3, 2013 at 16:51 Comment(4)
This seems to work (atleast in chrome) : document.getElementsByTagName('meta')['video'].getAttribute('content'); if the markup is as below: <meta name="video" content="http://video.com/video33353.mp4" />Alienism
@samdeV, this is the cleanest of all the solutions here. Submit it as your own answer. :)Lanceted
@samdeV, also you don't need to .getAttribute('content'), you can just .content: document.getElementsByTagName('meta')['video'].content. I just tested, this works fine in Firefox as well.Lanceted
I am now informed that it doesn't work in Safari. Damnit.Lanceted
L
10
document.querySelector('meta[property="video"]').content

this way you can get the content of the meta.

Lippert answered 12/4, 2021 at 18:16 Comment(0)
I
6

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.

Ill answered 7/1, 2018 at 11:11 Comment(1)
its awsome , i need this code just for csrf-tokenPerspire
A
5

Simple one, right?

document.head.querySelector("meta[property=video]").content
Arse answered 28/11, 2019 at 16:15 Comment(0)
S
3

My variant of the function:

const getMetaValue = (name) => {
  const element = document.querySelector(`meta[name="${name}"]`)
  return element?.getAttribute('content')
}
Scythe answered 18/4, 2020 at 13:53 Comment(0)
G
2

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/

Gametophore answered 5/2, 2015 at 11:10 Comment(0)
H
2

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"
Hackberry answered 29/4, 2015 at 14:23 Comment(0)
B
2
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;
}
Biggerstaff answered 22/7, 2015 at 3:46 Comment(0)
L
2

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);
Larocca answered 29/1, 2021 at 10:27 Comment(0)
G
2

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

Galligan answered 26/2, 2022 at 20:39 Comment(0)
C
1

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());
Clactonian answered 8/6, 2020 at 13:34 Comment(0)
S
0

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;
})();
Shikoku answered 1/10, 2016 at 11:45 Comment(0)
C
0

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.

Cronk answered 13/1, 2019 at 4:36 Comment(0)
P
0

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"
Paphian answered 6/4, 2022 at 15:31 Comment(0)
A
0

The problem with complex websites and metadata is that meta tags not always have the itemprop attribute. And in some case they have itemprop only but not a name attribute.

With this script you can get all the Meta with an itemprop attribute and print its content.

  const allMeta = document.getElementsByTagName("meta");
    
  for (let i = 0; i < allMeta .length; i++) {
      if( allMeta [i].getAttribute("itemprop") != null){
        console.log( allMeta [i].getAttribute("itemprop")+":"+allMeta [i].getAttribute('content') );
      }
  }
Amoreta answered 15/9, 2022 at 10:22 Comment(0)
I
0

It's very simple with vanilla-js...

var author = document.querySelector("meta[name=author]").content;
alert(`My author is ${author}`);
Important answered 1/9, 2023 at 21:47 Comment(0)
C
-1
<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

Cleromancy answered 9/12, 2019 at 13:15 Comment(0)
P
-2

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

Prior answered 21/6, 2021 at 17:15 Comment(1)
For Stackoverflow site purposes, your response needs to be more complete, with minimal explanation about your code.Foil
S
-3

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" />'
Sportswoman answered 30/7, 2019 at 8:9 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.