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?
It 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!');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With