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