Categories
JavaScript Answers

How to Use JavaScript to Change the meta Tags of the Web Page?

Spread the love

We can set the content property of each meta tag to change the content attribute value of each meta tag.

If we have the following meta tags:

<meta name='keywords'>  
<meta name='description'>

Then we can get the meta tags and change their contents by writing:

const meta = document.getElementsByTagName('meta')  
meta.keywords.content = "My new page keywords";  
meta.description.content = "My new page description"

We call document.getElementsByTagName with 'meta' to get both meta tags.

Then we set the meta tag with the name keywords by writing:

meta.keywords.content = "My new page keywords";

And we set the meta tag with the name description by writing:

meta.description.content = "My new page description"

Then we get:

<meta name="keywords" content="My new page keywords">  
<meta name="description" content="My new page description">

as a result.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *