javascript 通过选择`property`属性获取`Meta`属性`content`

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13451559/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 18:49:28  来源:igfitidea点击:

Get `Meta` attribute `content` by selecting `property` attribute

javascriptjquerymeta-tags

提问by curly_brackets

In jQuery you can do this:

在 jQuery 中,你可以这样做:

$("meta[property='fb:app_id']").attr("content");

Which will give you the contentattribute value from the meta-tag with propertyattribute "fb:app_id".

这将为您提供content来自meta带有property属性“fb:app_id”的-tag的属性值。

How can I do this in plain ol' Javascript?

我怎样才能在普通的 ol' Javascript 中做到这一点?

Thank you in advance. :-)

先感谢您。:-)

Kenneth

肯尼斯

回答by mccannf

Not as elegant as JQuery I'm afraid...

恐怕不如 JQuery 优雅...

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

回答by swade

document.querySelector('meta[property~="fb:app_id"][content]').content

回答by eyecatchUp

Note: Some use the propertyattribute:

注意:有些使用property属性:

<meta property="fb:app_id" content="1234567890">

whereas others use the nameattribute:

而其他人使用该name属性:

 <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.



同样的方法也可以用于其他所有元标记——只需更改闭包函数上的输入值(例如 fromfb:app_idfb:app_iddescriptiondescription)。

Edit:编辑:或者作为更通用的功能:

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