Javascript 在javascript中获取元数据属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29124579/
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-08-23 02:53:17  来源:igfitidea点击:

Get meta data attribute in javascript

javascriptmeta-tags

提问by Brad

I am having trouble retrieving information from a meta tag. I am trying to get an img src from a website and can't quite figure it out. Here is an example of what I am trying to do.

我无法从元标记中检索信息。我正在尝试从网站获取 img src,但无法弄清楚。这是我正在尝试做的一个例子。

<meta property="og:image" content="http://foo.jpg">
var image = document.querySelector('meta[property="og:image"]').getAttribute('content');

I have tried this but it doesn't work. Any ideas?

我试过这个,但它不起作用。有任何想法吗?

回答by T.J. Crowder

metaelements aren't special, you can query for them and get their attributes in the normal way.

meta元素并不特殊,您可以查询它们并以正常方式获取它们的属性。

In this case, here's how you'd get the contentattribute value from the first meta[property="og:image"]element:

在这种情况下,以下是content从第一个meta[property="og:image"]元素获取属性值的方法:

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

querySelectoris supported by all modern browsers, and also IE8.

querySelector所有现代浏览器以及 IE8 都支持。