Frage

Assume you are annoyed by my posts and want to hide all my comments from Stack Overflow. I know how to create a custom CSS to hide my username:

a[href$="what"] {
    display:none !important;
}

Unfortunately CSS does not allow me to refer to the parent element, so this will leave the text of the comment.

How can I hide the parent or preceding sibling to that link tag?


I'm not asking for a CSS selector! I know it doesn't exist. Please read the question before closing (and before providing answers that tell me what I already mentioned in my question).

I'm asking how you can select a DOM element in the absence of a relevant CSS selector. I believe there are JS solutions, but I can get none of them to work. Maybe there are other options, therefore I'm not asking for JS specifically. If you tell me how to parse the page with PHP and display it through another domain, that's completely fine with me.

Hints that Greasemonkey might do this are not helpful at all. Explain how to do it. Get it to work on your machine and post a detailed explanation. I couldn't get any of the available scripts to work.

War es hilfreich?

Lösung 3

Install Greasemonkey and then click this link to install the script.

The script makes use of jQuery and its body has only one line:

$('.comment:has(a.comment-user[href$="/what"])').remove()

Explanation: The code above can remove any element that is of class comment and has as its descendant a link that is of class comment-user and ends with /what.

Andere Tipps

You can't, as CSS has no means of selecting a parent node and applying a style to it. You'd need to use JavaScript for this. If specifically for creating user-modifiable layouts, likely via the Greasemonkey Firefox plugin (or similar plugin in a another browser).

Selectors Level 4 draft defines the subject of a selector, which allows you to use

!* > a[href$="what"] {  }
!* + a[href$="what"] {  }

However, AFAIK browsers don't support it yet.

And also note it's a feature of the complete Selectors profile, so it isn't extremely performance sensitive.

With JavaScript it's easy:

var comments = [].slice.call(document.querySelectorAll('a[href$="what"]'))
      .map(function(el){ return el.parentNode; })
      .filter(function(el){ return el.classList.contains('comment-body'); });

It does:

  1. Get all those anchors with querySelectorAll, and convert the resulting NodeList into an Array.
  2. Create a new array in which each element is the parentNode of the corresponding element in the previous array.
  3. Filter to remove elements that don't contain comments, e.g., the link at the bottom of your questions.
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top