首页 \ 问答 \ 你如何检查是否存在使用JavaScript的HTML元标记?(How do you check if a html Meta tag exist using JavaScript?)

你如何检查是否存在使用JavaScript的HTML元标记?(How do you check if a html Meta tag exist using JavaScript?)

所以我在我的HTML代码的头部有以下Meta标签

<html>
<head>
    <meta property="article:tag" content="This is an apple" />
    <meta property="article:tag" content="This is a pear" />
</head>

我想检查是否存在内容为“这是一个苹果”的元标记。 但由于某种原因,我的警报框始终运行正确。

if (document.querySelectorAll('meta[content="This is an apple"]') != null) {
  alert('Its here!');
}

有什么建议么?


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?

更新时间:2022-03-31 18:03

最满意答案

它将始终返回true,因为querySelectorAll在0匹配的情况下返回一个空数组。 文档

您可以使用NodeList对象的length属性来确定与指定选择器匹配的元素的数量

尝试这个:

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>


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>

相关问答

更多
  • 你走在正确的轨道上。 只需在适当的元素上使用.append()方法: var $meta = $('#HeadTitle'); if ($meta.length) { $('#optionalTitle > h2').append($meta.prop('content')); } 如果您希望替换内容而不是附加内容, .text()将更适合您。 You're on the right track. Just use the .append() method on the appropriate e ...
  • 测试元素是否存在。 不要获取元素,然后尝试读取你得到的任何东西的innerHTML(因为如果元素不存在,那将抛出异常) if (document.getElementById("tag_exist")) Test if the element exists. Don't fetch the element and then try to read the innerHTML of whatever you got back (since that will throw an exception if th ...
  • 添加soundEmbed.id = "__soundEmbed"; 在追加之前。 然后,用以下内容包围整个事物: if( !document.getElementById("__soundEmbed")) { soundEmbed = ......; ...... } Add soundEmbed.id = "__soundEmbed"; before appending. Then, surround the entire thing with: if( !document.getEle ...
  • 你可以使用这个: function getVideoContent() { var metas = document.getElementsByTagName('meta'); for (var i=0; i
  • 为有兴趣使用Handheld Group设备的任何其他人找到了该解决方案。 只需在文档的中包含标记即可。 在JavaScript中实现以下功能: