~/Remove DIV Elements With Tampermonkey

Sep 15, 2018


To remove specific div elements using Tampermonkey, use a script that targets those elements by class, id, or other selectors. Tampermonkey lets you inject custom JavaScript into web pages to alter content.

Install Tampermonkey from your browser extension store. Then create a new script with code like this to remove divs by class name:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
// ==UserScript==
// @name         Remove Specific DIVs
// @namespace    http://tampermonkey.net/
// @version      0.1
// @match        https://TARGET-WEBSITE.com/*
// @grant        none
// ==/UserScript==

(function() {
    var elements = document.querySelectorAll('div.classname'); // change selector as needed
    elements.forEach(function(div) {
        div.remove();
    });
})();

Replace 'div.classname' with a suitable CSS selector. For example, div#myid for an id or div.ad-banner for a class.

To run code after elements load via JavaScript frameworks, consider using a MutationObserver:

1
2
3
4
5
6
var observer = new MutationObserver(function(mutations) {
    document.querySelectorAll('div.classname').forEach(function(div) {
        div.remove();
    });
});
observer.observe(document.body, { childList: true, subtree: true });

Edit the @match field for your site and selector for your target divs. Save and reload the website to verify the divs are removed. For more info, consult the Tampermonkey documentation.

Tags: [tampermonkey] [javascript]