假设我想删除example.com上的一个div,但该站点使用随机的div类,匹配regex/[0-9a-z]{12}/(并在每次重新加载页面时更改)。
两个(相关的)问题:
首先,我如何删除每个div与类匹配的模式?每个div看起来像:
<div class="0123456789ab" ... > ... </div>
第二,如何删除匹配已知模式的特定div(比如"bottom")在下面的代码片段中)?
<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;
}
}
}