在JavaScript中获取元数据属性 [英] Get meta data attribute in javascript

查看:448
本文介绍了在JavaScript中获取元数据属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在从元标记中检索信息时遇到麻烦.我正在尝试从网站获取img src,但还不太清楚.这是我正在尝试做的一个例子.

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.

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

推荐答案

meta元素并不特殊,您可以通过常规方式查询它们并获取其属性.

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

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

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

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

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

querySelector.

querySelector is supported by all modern browsers, and also IE8.

这篇关于在JavaScript中获取元数据属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆