So I have the following Meta tag in the header of my HTML code
<html>
<head>
<meta property="article:tag" content="This is an apple" />
<meta property="article:tag" content="This is a pear" />
</head>
And I would like to check if the meta tag with the content "this is an apple" exists. But for some reason My alert box always runs true.
if (document.querySelectorAll('meta[content="This is an apple"]') != null) {
alert('Its here!');
}
Any suggestions?
So I have the following Meta tag in the header of my HTML code
<html>
<head>
<meta property="article:tag" content="This is an apple" />
<meta property="article:tag" content="This is a pear" />
</head>
And I would like to check if the meta tag with the content "this is an apple" exists. But for some reason My alert box always runs true.
if (document.querySelectorAll('meta[content="This is an apple"]') != null) {
alert('Its here!');
}
Any suggestions?
Share Improve this question asked Feb 16, 2017 at 16:38 MaritonMariton 6213 gold badges14 silver badges29 bronze badges 1- use the length property on result from querySelectorAll instead of checking if its null – Mukul Goel Commented Feb 16, 2017 at 16:41
2 Answers
Reset to default 5It will always return true because querySelectorAll
return an empty array in case of 0 match. Documentation
You can use the length property of the NodeList object to determine the number of elements that matches the specified selector
try this:
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>
document.querySelectorAll
returns an array. You want to check for its length, because if there are no matching elements, it returns []
(the empty array). So:
if (document.querySelectorAll('meta[content="This is an apple"]').length !== 0) {
alert('Its here!');
}