Search code examples
javascriptjqueryhtmlmeta-tags

How to check for existing meta tag before generating a new one with javascript (or jquery)?


I'm developing a widget that creates basic SEO tags that could already exist on a page so I'm wanting to make sure the widget checks for existing tags before the new tag is generated.

For example, one of the tags that the widget produces is

<meta name="description" content="Description of the webpage"/>

Since this tag is one that most pages already have, is there a way to use javascript to check for the tag before writing it?


Solution

  • Here is the plain Javascript solution (no libraries):

    Check for the meta description element using: document.querySelector("meta[name=description]");

    If found, access its content attribute using .getAttribute("content").

    Demo:

    if(document.querySelector("meta[name=description]")){
    
      if(document.querySelector("meta[name=description]").getAttribute("content") === "Description of the webpage")
    
        console.log("meta description with content 'Description of the webpage' found");
        // do something
    
    }
    else{
    
      console.log("meta description not found");
      // do something
    
    }
    <meta name="description" content="Description of the webpage"/>

    Read up:

    Source