首页 > 解决方案 > 通过正则表达式阻止 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>

先感谢您。

标签: javascriptuserscripts

解决方案


对于第一部分,您只需要遍历所有<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;
      }
    }
  }

推荐阅读