Blocking div by regex

Viewed 41

Suppose I want to remove a div on example.com, but the site uses random div classes which matches the regex /[0-9a-z]{12}/ (and change on every reload of the page).

Two (related) questions:

First, how do I remove every div with a class matching that pattern? Each div would look like:

<div class="0123456789ab" ... > ... </div>

Second, how do I remove a specific div that matches a known pattern (say "bottom" in the following snippet)?

<div class="0123456789ab" style="bottom: 0px; position: fixed; justify-content: center;">

[...]

</div>

Thank you in advance.

1 Answers

For the first part, you just need to go through all <div> elements and match their class names:

  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;
      }
    }
  }

To additionally check for inline style, you can just use getAttribute method which gives you the string value for an attribute:

  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;
      }
    }
  }
Related