Get meta data attribute in javascript

2020-05-28 22:28发布

问题:

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?

回答1:

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.