如何检查HTML元标记是否存在使用JavaScript?
问题描述:
所以我在我的HTML代码如何检查HTML元标记是否存在使用JavaScript?
<html>
<head>
<meta property="article:tag" content="This is an apple" />
<meta property="article:tag" content="This is a pear" />
</head>
头以下元标记,我想检查是否与内容元标记“这是苹果”存在。但由于某种原因,我的警报框始终运行正确。
if (document.querySelectorAll('meta[content="This is an apple"]') != null) {
alert('Its here!');
}
有什么建议吗?
答
它总会返回true,因为querySelectorAll
在0匹配的情况下返回一个空数组。 Documentation
可以使用NodeList对象的长度属性来确定
匹配指定的选择元素的个数试试这个:
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>
+0
我欣赏细节。你的解决方案非常棒! – Mariton
答
document.querySelectorAll
返回一个数组。你想检查它的长度,因为如果没有匹配的元素,它会返回[]
(空数组)。所以:
if (document.querySelectorAll('meta[content="This is an apple"]').length !== 0) {
alert('Its here!');
}
使用querySelectorAll的结果的长度属性,而不是检查它的空 –