如何使用JavaScript检查是否存在html元标记?

Mar*_*ton 3 html javascript

所以我在HTML代码的标题中有以下Meta标记

<html>
<head>
    <meta property="article:tag" content="This is an apple" />
    <meta property="article:tag" content="This is a pear" />
</head>
Run Code Online (Sandbox Code Playgroud)

我想检查内容为"这是一个苹果"的元标记是否存在.但由于某种原因,我的警报框始终运行正常.

if (document.querySelectorAll('meta[content="This is an apple"]') != null) {
  alert('Its here!');
}
Run Code Online (Sandbox Code Playgroud)

有什么建议?

Rya*_*ker 5

它总是返回true,因为querySelectorAll在0匹配的情况下返回一个空数组.文档

您可以使用NodeList对象的length属性来确定与指定选择器匹配的元素数

试试这个:

if (document.querySelectorAll('meta[content="This is not an apple"]').length > 0) {
    alert('Its here!');
} else {
    alert('Its not here')
}
Run Code Online (Sandbox Code Playgroud)
<head>
    <meta property="article:tag" content="This is an apple" />
    <meta property="article:tag" content="This is a pear" />
</head>
Run Code Online (Sandbox Code Playgroud)