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

筅森魡賤 提交于 2019-12-10 12:33:26

问题


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?


回答1:


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:

  • How to check if element exists in the visible DOM?
  • How do I get the information from a meta tag with javascript?

Source




回答2:


Sure its possible. Just use something like:

var description = $('meta[name=description]').attr("content");

Check the fiddle: https://jsfiddle.net/034ghy1y/




回答3:


This will return the first meta tag found on a page.

var tag = document.getElementsByTagName("meta")
  if(tag[0]) {
    console.log('found ' + tag[0]);
  } else {
    console.log("Not found")
  }

http://plnkr.co/edit/Gj9x5l8yS9xh2BoWkAm8?p=preview



来源:https://stackoverflow.com/questions/29647336/how-to-check-for-existing-meta-tag-before-generating-a-new-one-with-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!