如何在使用javascript(或jquery)生成新的元标记之前检查现有元标记? [英] How to check for existing meta tag before generating a new one with javascript (or jquery)?

查看:52
本文介绍了如何在使用javascript(或jquery)生成新的元标记之前检查现有元标记?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 =descriptioncontent = 网页说明/>

由于此标记是大多数网页已有的标记,有没有办法使用javascript在写之前检查标签?

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?

推荐答案

这是普通的Javascript解决方案(没有库):

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

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

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

If found, access its content attribute using .getAttribute("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?

来源

这篇关于如何在使用javascript(或jquery)生成新的元标记之前检查现有元标记?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆