Search code examples
javascripttampermonkey

script that applies a style to newly created elements


I am writing a tampermonkey script that changes the style of an element whose class starts with "blocked". So i have this code:

var blockedelements = document.querySelectorAll("[class^=blocked]");
var element = blockedelements[0];
element.style.display="none";

for simplicity this is only for the first element but i know how to iterate through each one and this code as it is works. the webapp dynamically creates new elements with this class and i want the script to execute for each newly created element which is what i don't know how to do. I want a pure JS solution, not jquery. Is this what a listener is for? i don't know much about javascript.

I would appreciate any pointers, thanks


Solution

  • Instead of manually changing the display value for every instance of the element, you could use JavaScript to add a page-wide style rule to hide all of them. That way you can let the browser handle applying the rule to both existing and future instances of the element for you.

    Rough idea:

    var rule = "[class^=blocked] { display: none }";
    var styleElement = document.createElement("style");
    
    styleElement.type = "text/css";
    
    if (styleElement.style.cssText) {
      styleElement.style.cssText = rule;
    } else {
      styleElement.appendChild(document.createTextNode(rule));
    }
    
    document.getElementsByTagName("head")[0].appendChild(styleElement);