How to get the information from a meta tag using JavaScript ?


To get the information from a meta tag using JavaScript, you can use the document.querySelector() method to select the meta tag by its name or property attribute, and then access its content attribute to retrieve the information.

Here are some examples:

  • Get the value of the description meta tag:
const description = document.querySelector('meta[name="description"]').getAttribute('content');
console.log(description);
  • Get the value of the og:title meta tag:
const title = document.querySelector('meta[property="og:title"]').getAttribute('content');
console.log(title);
  • Get the value of the viewport meta tag:
const viewport = document.querySelector('meta[name="viewport"]').getAttribute('content');
console.log(viewport);

Note that if the meta tag does not exist, the querySelector() method will return null, so you should check for that before accessing the content attribute to avoid errors.



About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.