0

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.

2
  • Just use an attribute selector in your css rule set. [data-test-id] { display: none; } will hide all elements with that attribute. Commented Jan 2, 2018 at 16:31
  • For hide/show see JavaScript hide/show element Commented Jan 2, 2018 at 16:34

1 Answer 1

9

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

Sign up to request clarification or add additional context in comments.

1 Comment

It is very helpful, thank you very much Andrew!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.