0

I'm trying to remove a div from this page with TamperMonkey.

This code works well with chrome DevTools console

var elems = document.getElementsByClassName('hdn hdb-m hfl-m');
elems[0].parentNode.removeChild(elems[0]);

but doesn't work with TamperMonkey

// ==UserScript==
// @name         New Userscript
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        http://*/*
// @grant        none
// ==/UserScript==

(function() {
    'use strict';
    var elems = document.getElementsByClassName('hdn hdb-m hfl-m');
    elems[0].parentNode.removeChild(elems[0]);
})();

What am I missing?

JJJohn
  • 425
  • 1
  • 10
  • 25

1 Answers1

0

I can't say exactly, but my educated guess is that the website generates some of its content by JavaScript after your script executes. By default, tampermonkey scripts execute when the page HTML is loaded and parsed. But so does most code that generates page by JavaScript. So you can see how your script might run before the element you want to delete is generated.

The laziest solution is to use some timer to delay the execution, but expect an ugly twitch as you remove the element after the timeout. Example:

function removeTheThing() {
    var elems = document.getElementsByClassName('hdn hdb-m hfl-m');
    elems[0].parentNode.removeChild(elems[0]);
}
setTimeout(removeTheThing, 1000);

The more advanced method would be to use MutationObserver, which can trigger code IMMEDIATELY as a change to the page occurs. You can try that, it's more work but way more elegant.

Tomáš Zato
  • 4,282
  • 14
  • 48
  • 77