0

I tried to write a greasemonkey script that would remove search results on Ebay that say 'Shipping not specified'. The code below removes only some of them and sometimes even those that have shipping cost specified or maybe it works on 1 item only. I don't even know anymore. What is wrong?

    // ==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 li = document.getElementsByClassName('lvshipping');

    for(var i=0;i < li.length;i++)
    {
        if(li[i].innerHTML.indexOf("Shipping not specified") != -1)
        {
            console.log("Found!!!!!!!!!!!!!!!");
            li[i].parentNode.parentNode.parentNode.removeChild(li[i].parentNode.parentNode);
        }
    }
})();

Keep it simple.

SinsBird
  • 3
  • 3

1 Answers1

0

Try looping backwards:

for (var i = li.length; i-->0 ;)

I think document.getElementsByClassName returns you a dynamic NodeList. So when you remove the current <li> from the document, then it will also be removed from the list, shifting the next <li> into position i. The iterator's i++ will then skip over that element without processing it.

joeytwiddle
  • 29,306
  • 13
  • 121
  • 110
  • Yes, this works, thanks, but can you explain this syntax? How is it different from for(var i=li.length;i>0;i--) ? – SinsBird May 01 '16 at 14:43
  • We want to loop from `li.length-1` to `0`. But what you have will loop from `li.length` to `1`. You need to `i--` before the first iteration of the loop, which I did in the "condition" term. [Explanation here](http://stackoverflow.com/a/23430396/99777) – joeytwiddle May 01 '16 at 18:13
  • 1
    The OP could also use `document.querySelectorAll` which returns a static Node List. – Jeremy J Starcher May 08 '16 at 20:08