Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove links from a page via JavaScript?

I want to write a user script for my browsers (Opera, Chromium) that removes links containing predefined keywords. For example, a link <a href="foo">bar</a> should simply vanish from the page when foo is part of the blacklist.

How do i remove duplicate links from a page except first shows how to get and filter a site, but I want to do this directly via a user script. Any ideas how I would apply the filter on every page load?

like image 237
htorque Avatar asked Nov 15 '25 01:11

htorque


1 Answers

Get the document.links collection. If any of their .href properties match your blacklist, set their style.display property to 'none'.

e.g.

function removeLinks () {
  var blackList = /foo|bar|baz/;
  var link, links = document.links;
  var i = links.length;

  while (i--) {
    link = links[i];
    if (blackList.test(link.href)) {
      link.style.display = 'none';
    }
  }
}

Edit

To remove duplicate links is a similar exercise. First convert the links HTMLCollection to a plain array, then as you iterate over them use their hrefs as create properties of an object. If the href is already a property, hide it using the above method or link.parentNode.removeChild(link).

like image 99
RobG Avatar answered Nov 17 '25 20:11

RobG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!