Explain Codes LogoExplain Codes Logo

How do I get the information from a meta tag with JavaScript?

javascript
meta-tags
dom-manipulation
javascript-functions
Anton ShumikhinbyAnton Shumikhin·Sep 17, 2024
TLDR

Here's your trusty JavaScript sidekick in action, retrieving the content of a description meta tag:

// Say hello to your data const content = document.querySelector('meta[name="description"]').content; console.log(content); // "Hello, World! Or rather, hello... description!"

This little snippet targets the <meta> tag by its name attribute. But what about a property attribute? Just a minor adjustment needed:

// Property, meet your match const content = document.querySelector("meta[property='og:description']").content; console.log(content); // "That's some quality Open Graph description you got there!"

Starting points: Dealing with different attributes

name attributes

When tackling name attributes, this is how you might go about it:

// Show me the KEYWORDS! const keywords = document.querySelector('meta[name="keywords"]').content; console.log(keywords);

property attributes

If you're wrestling with property attributes instead, give this a whirl:

// Gotta fetch 'em all! Starting with the OG title. const ogTitle = document.querySelector('meta[property="og:title"]').content; console.log(ogTitle);

Playing the field: Iterating through meta tags

Need a sweep through all your meta tags? JavaScript has your back:

// Meta tags, come out, come out, wherever you are! const metas = document.getElementsByTagName('meta'); for (let meta of metas) { if (meta.getAttribute('property') === 'og:title') { console.log(meta.getAttribute('content')); } }

The handyman: A reusable retrieval function

There's always room for a durable and reusable function. Here's one made for any meta tag:

// This... IS... GETCONTENT()! function getMetaContentByName(name, contentName = 'content') { const tag = document.querySelector(`meta[name="${name}"]`); return tag && tag.getAttribute(contentName) || ''; }

Safety first: Null check and error prevention

Keep your code crash-free with null checks:

// I ain't afraid of no NULL const metaContent = getMetaContentByName('description'); if (metaContent) { console.log(metaContent); } else { console.log('Hmm, leaves me hungry. Can\'t eat NULL for lunch!'); }

On the lookout for dynamic content

When Agent JavaScript is up against dynamically generated content, it's time to await DOM updates or deploy the MutationObserver.

Multipurpose meta retrieval

Want to fetch an array of meta content swiftly? Charm JavaScript into doing the job:

['description', 'keywords', 'og:title'].forEach(name => { console.log(getMetaContentByName(name)); });

The bigger picture: SEO and accessibility

Bare in mind, the secret sauce for SEO and accessibility is the well-seasoned meta content. So, mastering this skill is akin to ruling the web world.