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

Time:10-26

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?

CodePudding user response:

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");

CodePudding user response:

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>

CodePudding user response:

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)
    }
});
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related