Search code examples
javascripthtmlcssgreasemonkeygreasemonkey-4

Using Javascript to hide elements with specific data-test-id value


I often use a simple Greasemonkey JS script to hide elements on web pages - this is a basic one I use to hide some ads on Yahoo Mail which are in DIVs with a specific ID:

function addGlobalStyle(css) {
    var head, style;
    head = document.getElementsByTagName('head')[0];
    if (!head) { return; }
    style = document.createElement('style');
    style.type = 'text/css';
    style.innerHTML = css;
    head.appendChild(style);
}

addGlobalStyle(" #slot_LREC, #slot_LREC4 { display:none; }");

The issue I have is that quite a lot of content in Yahoo Mail doesn't have a generic Class or ID, but instead has a data-test-id value - e.g.

<a data-test-id="pencil-ad" class="something_very_complicated">example</a>

I wondered if there's any way to create a variant of the addGlobalStyle function to hide elements where an element has a specific data-test-id value?

I don't have the option of using jQuery - or at least, I don't know how to add jQuery into the GM script...

As far as I can tell, this isn't a duplicate of javascript: select all elements with "data-" attribute (without jQuery) because I am trying to hide only one element where the data-test-id attribute has a certain value. I'm not trying to hide all elements which have a data-test-id attribute.


Solution

  • You can select based on attributes like this.

    I'm selecting all the elements with data-test-id=cheese and then I'm using a for of to hide them.

    let elements = document.querySelectorAll('[data-test-id=cheese]');
    
    for (let element of elements) {
      element.style.display = "none";
    }
    div {
      height: 100px;
      margin: 5px 0px;
      background: tomato;
      line-height: 100px;
      text-align: center;
      color: white;
      font-size: 20px;
    }
    <div>1</div>
    <div>2</div>
    <div data-test-id="cheese">3</div>
    <div>4</div>
    <div data-test-id="cheese">5</div>
    <div>6</div>
    <div data-test-id="cheese">7</div>
    <div>8</div>

    You can, of course, do this without any javascript too by adding this bit of CSS

    div {
      height: 100px;
      margin: 5px 0px;
      background: tomato;
      line-height: 100px;
      text-align: center;
      color: white;
      font-size: 20px;
    }
    
    [data-test-id=cheese] {
      display: none
    }
    <div>1</div>
    <div>2</div>
    <div data-test-id="cheese">3</div>
    <div>4</div>
    <div data-test-id="cheese">5</div>
    <div>6</div>
    <div data-test-id="cheese">7</div>
    <div>8</div>

    Both snippets do the same thing.

    Hope this is helpful