Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get meta data attribute in javascript

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?

like image 702
Brad Avatar asked Mar 18 '15 14:03

Brad


People also ask

How do I get a meta tag?

If you want to find out whether a given page is using meta tags, just right-click anywhere on the page and select “View Page Source.” A new tab will open in Chrome (in Firefox, it'll be a pop-up window). The part at the top, or “head” of the page, is where the meta tags would be.

What is meta data in Javascript?

Metadata is data (information) about data. <meta> tags always go inside the <head> element, and are typically used to specify character set, page description, keywords, author of the document, and viewport settings. Metadata will not be displayed on the page, but is machine parsable.

What is a meta description for a website?

A meta description tag generally informs and interests users with a short, relevant summary of what a particular page is about. They are like a pitch that convince the user that the page is exactly what they're looking for.


1 Answers

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

like image 174
T.J. Crowder Avatar answered Sep 18 '22 08:09

T.J. Crowder