最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin3浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 5

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!');
}
发布评论

评论列表(0)

  1. 暂无评论