Skip to content

Instantly share code, notes, and snippets.

@bogorad
Last active March 15, 2025 21:22
Show Gist options
  • Save bogorad/b677bacdb49a9eed4fdb4665dea5caba to your computer and use it in GitHub Desktop.
Save bogorad/b677bacdb49a9eed4fdb4665dea5caba to your computer and use it in GitHub Desktop.
block x ads, tampermonkey script
// ==UserScript==
// @name Block Ad Elements on Twitter/X
// @namespace http://tampermonkey.net/
// @version 1.1
// @description Block parent elements containing the word "Ad" and monitor dynamic content changes
// @author You
// @match https://twitter.com/i/litst*
// @match https://x.com/i/lists/*
// @match https://x.com/home
// @match https://x.com/*/status
// @exclude https://x.com/i/grok
// @grant none
// ==/UserScript==
(function() {
'use strict';
// Function to find and remove elements containing the word "Ad"
function blockAdElements() {
// Select all span elements
const spans = document.querySelectorAll('span');
spans.forEach(span => {
// Check if the span contains the word "Ad"
if (span.textContent.includes('Ad')) {
// Traverse up the DOM tree to find the parent element 6 levels up
let parent = span.parentElement;
for (let i = 0; i < 6 && parent; i++) {
parent = parent.parentElement;
}
// If the parent element exists, remove it
if (parent) {
parent.remove();
}
}
});
}
// Run the function initially
blockAdElements();
// Set up a MutationObserver to handle dynamic content
const observer = new MutationObserver(mutations => {
mutations.forEach(() => {
blockAdElements();
});
});
// Start observing the document body for changes
observer.observe(document.body, { childList: true, subtree: true });
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment