javascript - 通过正则表达式阻止 div
问题描述
假设我想删除 example.com 上的一个 div,但该站点使用与正则表达式 /[0-9a-z]{12}/ 匹配的随机 div 类(并在每次重新加载页面时更改)。
两个(相关)问题:
首先,如何删除具有匹配该模式的类的每个 div?每个 div 看起来像:
<div class="0123456789ab" ... > ... </div>
其次,如何删除与已知模式匹配的特定 div(在以下代码段中说“底部”)?
<div class="0123456789ab" style="bottom: 0px; position: fixed; justify-content: center;">
[...]
</div>
先感谢您。
解决方案
对于第一部分,您只需要遍历所有<div>
元素并匹配它们的类名:
const divs = document.querySelectorAll("div");
const regex_className = /^[0-9a-z]{12}$/i;
// for each div
for(const div of divs) {
for(const className of div.classList) {
// if one of the class names matches the regex
if(regex_className.test(className)) {
// do something with div
console.log(div);
// do not process this div again for more class names
break;
}
}
}
要另外检查内联样式,您可以使用getAttribute
为您提供属性字符串值的方法:
const divs = document.querySelectorAll("div");
const regex_className = /^[0-9a-z]{12}$/i;
const regex_inlineStyle = /^bottom/i;
const checkInlineStyle = (divToCheck, styleRegex) => {
// check if any value is present, if not then we certainly have no match
if(divToCheck.hasAttribute("style")) {
return styleRegex.test(divToCheck.getAttribute("style"));
}
return false;
};
// for each div
for(const div of divs) {
for(const className of div.classList) {
// if one of the class names matches the regex
if(regex_className.test(className) && checkInlineStyle(div, regex_inlineStyle)) {
// do something with div
console.log("Found div",div);
// do not process this div again for more class names
break;
}
}
}
推荐阅读
- javascript - 如何有效且高效地将项目分组到成对的存储桶中(如果存在)
- mongodb - 日期范围在聚合管道中不起作用,但在 find() 中起作用
- python - SqlAlchemy“contains_eager”似乎没有加载嵌套关系
- google-cloud-platform - Sqoop 作业通过 Dataproc 失败
- node.js - 无法在 express api 和反应应用程序中使用 http-proxy-middleware 进行代理
- powershell - 有没有办法获得大于 int32 的数字范围?
- java - 警报对话框的 XML?
- python - 如何在 Python 中准确获取币安 API 价格?
- angular - 如何将我的 Angular 4 产品专门迁移到 Angular 7 程序而不是最新的程序
- quickbooks - 使用 Consolibyte Quickbooks Web 连接器,我如何将两套书籍分开?