Search code examples
javascriptgreasemonkey

How to hide an element using Greasemonkey


I'm looking to permanently hide an element on this website I visit. I know this can be done with Greasemonkey, but I don't know how to do it.

Here is the code:

<div class="col-xs-12 col-sm-3">
<div class="widget-box">
<div class="widget-content">

<div id="40496">


<center>

<div class="alert alert-info">Coins: 4</div>

<span style="font-size:0.8em;" class="external-event ui-draggable label label-danger">Anti-Bots ne pas cliquer</span>
<img src="http://www.somesite.com/wp-content/uploads/2016/01/no_bots.jpeg" class="follower" width="150" height="112.5" border="0"><br><br>

What I need is to hide this entire element, but the reason it's hidden must be the img src or the "Anti-Bots ne pas cliquer" text. If I use any of the divs to hide it, or ID or anything else, it will hide content that I don't want hidden also. The img src or that text must be the association why the script will hide the element.

I hope I'm clear and that anyone can help.


Solution

  • Finding the img with a specific src can be done using an attribute selector that is passed to document.querySelectorAll to find all instances. We can then manually check if there is a span with the offending text somewhere in the div. The div can be found by considering the parentElement until we find one with class col-xs-12.

    Finally, everything must be executed only after the page has loaded. The result is as follows.

    window.addEventListener('load', () => {
      var imgs = document.querySelectorAll('img[src="http://www.somesite.com/wp-content/uploads/2016/01/no_bots.jpeg"]');
      for (let img of imgs) {
        // find enclosing .col-xs-12
        let el = img;
        while (!el.classList.contains('col-xs-12')) {
          el = el.parentElement;
        }
        // find spans, check if one has the offending text
        let spans = el.querySelectorAll('span');
        for (let span of spans) {
          if (span.textContent === 'Anti-Bots ne pas cliquer') {
            el.parentElement.removeChild(el); // this deletes the div
            //el.style.display = 'none'; // this hides the div
            break;
          }
        }
      }
    });
    <p>I should not be hidden.</p>
    <div class="col-xs-12 col-sm-3">
    <div class="widget-box">
    <div class="widget-content">
    
    <div id="40496">
    
    
    <center>
    
    <div class="alert alert-info">Coins: 4</div>
    
    <span style="font-size:0.8em;" class="external-event ui-draggable label label-danger">Anti-Bots ne pas cliquer</span>
    <img src="http://www.somesite.com/wp-content/uploads/2016/01/no_bots.jpeg" class="follower" width="150" height="112.5" border="0"><br><br>