1

I was trying to create a greasemonkey script which removes Facebook and twitter from a website. In my case 9gag. I looked and I need to hide the classes:

1. 'social-action' (works fine)
2. 'badge-sticky-social sticky-social' (every second post)
3. 'post-afterbar-a in-list-view' (every second post)

my Code so far (differing classes)

(function() {
   var ads=document.getElementsByClassName('badge-sticky-social sticky-social');
   for (var i=0; i<ads.length; i++) {
      ads[i].parentNode.removeChild(ads[i]);
   }
})()

I don't know why it only works on half the post and not all of them

bad_coder
  • 11,289
  • 20
  • 44
  • 72

1 Answers1

0

Because you're removing the very elements that you're iterating over, the iteration ends up in the wrong place. That is, you look at the first one and then remove it, and then try to look at the second one. But the one that had been the second one is now the first one, so that one gets skipped.

The solution, as CBroe says, is to run the loop from high to low, so that you're not trying to count things that already have been removed:

for (var i=ads.length-1; i>=0; i--)
Jacob Mattison
  • 50,258
  • 9
  • 107
  • 126
  • Correct – because NodeLists are “live”, they always reflect the current state of the DOM. Easy fix: Let the loop run the other way around: `for (var i=ads.length-1; i>0; i--) { …` – CBroe Dec 09 '13 at 19:30
  • Absolutely, except that you need i>=0, so that you get the first one. – Jacob Mattison Dec 09 '13 at 19:34
  • that was fast thanks. works now :-) but another problem is that the site loads new post when I'm at the bottom of the page. the script won't apply to the new ones. – user3084141 Dec 09 '13 at 19:49