Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 985
Mariton Avatar asked Feb 05 '23 02:02

Mariton


2 Answers

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>
like image 94
Ryad Boubaker Avatar answered Feb 07 '23 17:02

Ryad Boubaker


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!');
}
like image 33
Aurel Bílý Avatar answered Feb 07 '23 18:02

Aurel Bílý