Mariton
Mariton

Reputation: 621

How do you check if a html Meta tag exist using JavaScript?

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?

Upvotes: 4

Views: 2961

Answers (2)

Ryad Boubaker
Ryad Boubaker

Reputation: 1501

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>

Upvotes: 5

Aurel B&#237;l&#253;
Aurel B&#237;l&#253;

Reputation: 7963

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!');
}

Upvotes: 3

Related Questions