In jQuery you can do this:
$("meta[property='fb:app_id']").attr("content");
Which will give you the content
attribute value from the meta
-tag with property
attribute "fb:app_id".
How can I do this in plain ol' Javascript?
Thank you in advance. :-)
Kenneth
Not as elegant as JQuery I'm afraid...
var metaTags=document.getElementsByTagName("meta");
var fbAppIdContent = "";
for (var i = 0; i < metaTags.length; i++) {
if (metaTags[i].getAttribute("property") == "fb:app_id") {
fbAppIdContent = metaTags[i].getAttribute("content");
break;
}
}
console.log(fbAppIdContent);
document.querySelector('meta[property~="fb:app_id"][content]').content
Note: Some use the property
attribute:
<meta property="fb:app_id" content="1234567890">
whereas others use the name
attribute:
<meta name="fb:app_id" content="1234567890">
I use the following to get the value from both variants:
var appId = (function(c) { for (var a = document.getElementsByTagName("meta"), b = 0;b < a.length;b++) {
if (c == a[b].name || c == a[b].getAttribute("property")) { return a[b].content; } } return false;
})("fb:app_id");
console.log(appId); //(bool)false if meta tag "fb:app_id" not exists.
The same can be used for every other meta tag as well - just change the input value on the closure function (eg. from
fb:app_id
to
description
).
Edit: Or as a more generic function:
function getContentByMetaTagName(c) {
for (var b = document.getElementsByTagName("meta"), a = 0; a < b.length; a++) {
if (c == b[a].name || c == b[a].getAttribute("property")) { return b[a].content; }
} return false;
}
console.log(getContentByMetaTagName("og:title"));