Javascript 用正则表达式阻塞div
假设我想删除example.com上的一个div,但是该站点使用与regex/[0-9a-z]{12}/(并且在每次重新加载页面时都会更改)匹配的随机div类 两个(相关)问题: 首先,如何删除每个具有与该模式匹配的类的div?每个div看起来像:Javascript 用正则表达式阻塞div,javascript,userscripts,Javascript,Userscripts,假设我想删除example.com上的一个div,但是该站点使用与regex/[0-9a-z]{12}/(并且在每次重新加载页面时都会更改)匹配的随机div类 两个(相关)问题: 首先,如何删除每个具有与该模式匹配的类的div?每个div看起来像: <div class="0123456789ab" ... > ... </div> 。。。 其次,如何删除与已知模式匹配的特定div(在下面的代码段中说“bottom”) [...] 提前感谢。对
<div class="0123456789ab" ... > ... </div>
。。。
其次,如何删除与已知模式匹配的特定div(在下面的代码段中说“bottom”)
[...]
提前感谢。对于第一部分,您只需要遍历所有
元素并匹配它们的类名:
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;
}
}
}
非常感谢。这非常有效(至少第一部分-我还没有测试第二部分)。
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;
}
}
}