如何在使用 javascript(或 jquery)生成新元标记之前检查现有元标记?

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

我正在开发一个小部件,它可以创建页面上可能已经存在的基本 SEO 标签,因此我想确保小部件在生成新标签之前检查现有标签。

例如,小部件生成的标签之一是

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

由于这个标签是大多数页面已有的标签,有没有办法在写入之前使用 javascript 检查标签?

这将 return 在页面上找到的第一个元标记。

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

当然有可能。只需使用类似:

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

勾选 fiddle: https://jsfiddle.net/034ghy1y/

这是简单的 Javascript 解决方案(没有库):

使用以下方法检查元描述元素: document.querySelector("meta[name=description]");

如果找到,请使用 .getAttribute("content") 访问其 content 属性。

演示:

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"/>

阅读:

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

Source