javascriptbookmarklet

What is wrong with the bookmarklet that is supposed to delete some element on specific page?


The following bookmarklet should remove a specific element from web-page opened in Chrome (I plan to use it on single webpage only, so there would be no need for a more general solution; also, I am interested in solution that would not be run automatically, hence the bookmarklet):

javascript: function run() { var r = "/html/body/div/div[1]"; var e = document.getElementByXpath(r); e.parentNode.removeChild(e) }; run();

It does not work, though.

Full disclosure: I have never written a single line of JS code before (so I would appreciate both explanation of what is wrong and correction), the bookmarklet is a simplified variant of the one suggested in the accepted answer of this thread.


Solution

  • You could try this:

    javascript: { try { document.querySelector('body > div > div:nth-child(1)').remove() } catch {} }
    

    Allow me to explain the code:

    javascript: {
     try {
      document.querySelector('body > div > div:nth-child(1)').remove();
     } catch {}
    }
    

    First, we replace document.getElementByXpath() because the document doesn't have that function. Instead of an XPath, we'll use CSS selectors. CSS selectors are like an XPath, but they look different -- and you can do more with them (like selecting multiple elements).

    That selector will look for every element that is the first child of a div in the body element. To limit it to one (the first one it finds) we use `document.querySelector()'. Using that will select only the first one found.

    If you want to find every element that matches that, you would use document.querySelectorAll() and loop through each element found.

    Incidentally, that code could look something like this:

    javascript: {
     for(var element of document.querySelectorAll('body > div > div:nth-child(1)')) {
      element.remove();
     }
    }
    

    Finally, why use the try catch block? A try...catch statement basically just says, if this code fails, do what I want with the error. In this case, catch is empty so we're just saying that we don't want anything to happen if there's an error.

    Hopefully this information is useful!