How to use greasemonkey to selectively remove content from a website

For questions like this, post a link to the target page. Or, if that is really not possible, save the page to pastebin.com and link to that.

Anyway, the general answer to your question is not too hard with the jQuery contains() selector. Something like this will work:

// ==UserScript==
// @name     _Remove annoying divs
// @include  http://YOUR_SERVER/YOUR_PATH/*
// @require  http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
// @grant    GM_addStyle
// ==/UserScript==
//- The @grant directive is needed to restore the proper sandbox.

/*--- Use the jQuery contains selector to find content to remove.
    Beware that not all whitespace is as it appears.
*/
var badDivs = $("div div:contains('Annoying text, CASE SENSITIVE')");

badDivs.remove ();

//-- Or use badDivs.hide(); to just hide the content.


Update for the newly clarified question/code:

In your specific example, you would use this:

var badDivs = $("div.entry div.foo:contains('Yes')");

badDivs.parent ().remove ();


Update for the site specified in the comments:
Note that there is no need to search for text because the site conveniently gives the key div a class of isHot or notHot.

// ==UserScript==
// @name     _Unless they're hot, they're not (shown).
// @include  http://www.ratemyprofessors.com/SelectTeacher.jsp*
// @require  http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
// @grant    GM_addStyle
// ==/UserScript==
//- The @grant directive is needed to restore the proper sandbox.

var badDivs = $("#ratingTable div.entry").has ("div.notHot");

badDivs.remove ();


Finally, for dynamic (AJAX driven) pages,

use MutationObserver or waitForKeyElements. (WaitForKeyElements also works fine on static pages.)

Here’s the above script rewritten to be AJAX aware:

// ==UserScript==
// @name     _Unless they're hot, they're not (shown).
// @include  http://www.ratemyprofessors.com/SelectTeacher.jsp*
// @require  http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
// @require  https://gist.github.com/raw/2625891/waitForKeyElements.js
// @grant    GM_addStyle
// ==/UserScript==
//- The @grant directive is needed to restore the proper sandbox.

waitForKeyElements ("#ratingTable div.entry", deleteNotHot);

function deleteNotHot (jNode) {
    if (jNode.has("div.notHot").length) {
        jNode.remove ();
    }
}

Leave a Comment