javascript - 检查文档是否包含类似于 Javascript 中指定字符串的类
问题描述
我正在尝试查找包含“广告”的所有元素。
如:
<iframe class="container" /> <!-- False -->
<a class="adp" /> <!-- True -->
<a class="adleft" /> <!-- True -->
<a class="some-other-class" /> <!-- False -->
我可以使用forEach
吗?我感谢大家的帮助。
解决方案
您可以通过使用语法来简单地通过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 标记无效。
推荐阅读
- c++ - 如何在 QTableView 中编辑选定的数据/行?
- python - 在 sqlalchemy 中删除具有 ENUM 类型的列的表
- c++ - 使用 std::optional 来避免潜在的未初始化变量?
- c# - NET 核心 webapi:为什么我会通过这个特定的 API 请求得到 404?
- javascript - 如何在 javascript 中全局捕获 net::ERR_NAME_NOT_RESOLVED
- python - 函数调用堆栈:模型拟合的 train_function 错误
- sharepoint-2013 - 列表项附件的 SharePoint 事件接收器已更新
- python - Matplotlib - 从数据框中的列在条形图上添加值标签
- flutter - Dart Analyzer 已停止工作,但我的代码中没有看到任何错误
- stored-procedures - 从 java oracle rdb 7.4 版本调用存储过程时出现问题