문제

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

도움이 되었습니까?

해결책

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--)
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top