Millhorn
Millhorn

Reputation: 3176

How to change multiple meta tag descriptions with a single variable (vanilla JS)?

I have the following meta tags on my website:

<meta name="description" content="content here" />
<meta itemprop="description" content="content here">
<meta property="og:description" content="content here" />

All 3 of these meta properties are necessary on my site. However, is there a way to reference a single description in a JS variable that I can pass to each of these content attributes?

Upvotes: 0

Views: 619

Answers (3)

Mustak Ahmed Khan
Mustak Ahmed Khan

Reputation: 1

let text = 'hello world';


let Allmeta = document.querySelectorAll('meta');

Allmeta.forEach((meta) => {
    if (meta.getAttribute('name') == 'description' || meta.getAttribute('itemprop') == 'description' || meta.getAttribute('property') == 'og:description') {
        meta.setAttribute('content',text)
    }
});

Upvotes: 0

Aidan
Aidan

Reputation: 60

Here is a simple method of doing this

<meta class="meta" name="description" content="content here" />
<meta class="meta" itemprop="description" content="content here">
<meta class="meta" property="og:description" content="content here" />
<script>
    document.querySelectorAll(".meta").forEach((el) => {
        el.setAttribute("content", "your content");
    })
</script>

Upvotes: 1

Maik Lowrey
Maik Lowrey

Reputation: 17594

You can use the querySelector with meta[key=value] and then set Attribute with setAttribute(key,value).

document.querySelector("meta[name='description'" ).setAttribute("content", "some new meta description");

document.querySelector("meta[itemprop='description'" ).setAttribute("content", "some new meta description");

document.querySelector("meta[property='description'" ).setAttribute("content", "some new meta description");

Upvotes: 2

Related Questions