如何使用JavaScript检查HTML中是否存在Meta标签?

4
所以我在HTML代码的头部有以下元标记。
<html>
<head>
    <meta property="article:tag" content="This is an apple" />
    <meta property="article:tag" content="This is a pear" />
</head>

我想检查是否存在内容为"this is an apple"的meta标签。但出于某种原因,我的提示框总是运行为真。

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

有什么建议吗?

使用querySelectorAll返回的结果的length属性,而不是检查它是否为null。 - Mukul Goel
2个回答

5

querySelectorAll如果没有找到匹配的元素,会返回一个空数组,因此该条件判断始终为真。 文档

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

尝试一下:

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


非常感谢您提供的详细信息,您的解决方案非常好! - Mariton

3

document.querySelectorAll 返回一个数组。你需要检查它的长度,因为如果没有匹配的元素,它会返回[](空数组)。因此:

if (document.querySelectorAll('meta[content="This is an apple"]').length !== 0) {
    alert('Its here!');
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接