最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Get meta data attribute in javascript - Stack Overflow

programmeradmin5浏览0评论

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="">
var image = document.querySelector('meta[property="og:image"]').getAttribute('content');

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

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?

Share Improve this question edited Jun 29, 2016 at 17:57 Brad asked Mar 18, 2015 at 14:20 BradBrad 811 gold badge2 silver badges6 bronze badges 1
  • 1 <meta> is an element, property is an attribute. you'd want something more like meta = document.getElementsByTagName('meta'), scan through that for your og:image attribute, then get the associated content. – Marc B Commented Mar 18, 2015 at 14:23
Add a comment  | 

1 Answer 1

Reset to default 24

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

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

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

Note that the content property is also available as a reflected property, so you can just use .content rather than .getAttribute("content"):

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

In modern JavaScript you can use the optional chaining operator (?.) to combine those two statements:

const content = document.querySelector('meta[property~="og:image"]')?.content;
// −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^

If the element isn't found, content will get the value undefined; otherwise, it'll get the value of the reflected property (which is the attribute value).

发布评论

评论列表(0)

  1. 暂无评论