首页 > 解决方案 > 检查文档是否包含类似于 Javascript 中指定字符串的类

问题描述

我正在尝试查找包含“广告”的所有元素。

如:

<iframe class="container" /> <!-- False -->
<a class="adp" /> <!-- True -->
<a class="adleft" /> <!-- True -->
<a class="some-other-class" /> <!-- False -->

我可以使用forEach吗?我感谢大家的帮助。

标签: javascripthtmlcss

解决方案


您可以通过使用语法来简单地通过querySelectorAll属性选择器的组合来实现这一点。[attr*=value]

上面的属性选择器语法将像这样工作:

表示具有属性名称的元素,其属性名称attr在字符串value中至少出现一次。value

上述解决方案的结果组合将是这样的:

document.querySelectorAll("[class*='ad']");

它为您提供了在其类名中包含广告的所有元素。然后,您可以简单地使用简单的循环或数组助手Array#forEach来使用结果。请注意,前面的结果将产生一个HTMLCollection,它需要在使用数组助手之前转换为数组,否则您可以使用传统的for循环对其进行处理。

最终代码应如下所示:

const ads = document.querySelectorAll("[class*='ad']");

Array.from(ads).forEach(el => {
  console.log(el);
})
<iframe class="container"></iframe>
<a class="adp"></a>
<a class="adleft"></a>
<a class="some-other-class"></a>

注意:您总是需要正确打开和关闭 HTML 标签,尤其是iframe. 由于它没有被假定为自闭合标签,因此会导致 HTML 标记无效。


推荐阅读