Skip to content

Instantly share code, notes, and snippets.

@yanyaoer
Created September 22, 2025 05:22
Show Gist options
  • Save yanyaoer/7ddaad2be7257a5faa8f09dcda4902d6 to your computer and use it in GitHub Desktop.
Save yanyaoer/7ddaad2be7257a5faa8f09dcda4902d6 to your computer and use it in GitHub Desktop.
userscripts
// ==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")) {
console.log("find node cleanup: ", span);
// console.log('parent cleanup: ', span.closest("article"))
// 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(() => {
// if (mutation.type === "childList") {
console.log("start cleanup: looping");
blockAdElements();
// }
});
});
// Start observing the document body for changes
observer.observe(document.body, { childList: true, subtree: true });
console.log("start cleanup: init");
document.addEventListener("DOMContentLoaded", function (ev) {
console.log("start cleanup: onReady");
blockAdElements();
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment