Search code examples
javascriptxpathoptimizationhtml-tablegreasemonkey

Need help optimizing script that hides table rows


I made this Greasemonkey script:

var maxpi = 250;
var p1 = "/html/body/div/div[2]/div/div[2]/table[2]/tbody/tr[1]/td[11]";
var p2 = "/html/body/div/div[2]/div/div[2]/table[2]/tbody/tr[2]/td[11]";
..
var p25 = "/html/body/div/div[2]/div/div[2]/table[2]/tbody/tr[25]/td[11]";

var r1 = "/html/body/div/div[2]/div/div[2]/table[2]/tbody/tr[1]";
var r2 = "/html/body/div/div[2]/div/div[2]/table[2]/tbody/tr[2]";
..
var r25 = "/html/body/div/div[2]/div/div[2]/table[2]/tbody/tr[25]";

var xpathPI1 = document.evaluate(p1, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
..
var xpathPI25 = document.evaluate(p25, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);

var xpathrow1 = document.evaluate(r1, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
..
var xpathrow25 = document.evaluate(r25, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);

if (xpathPI1.singleNodeValue.textContent >maxpi ){
xpathrow1.singleNodeValue.style.display='none';}
..
if (xpathPI25.singleNodeValue.textContent >maxpi ){
xpathrow25.singleNodeValue.style.display='none';}


Basically, it checks a table row's 11th field and if its contents > than 250 it hides the row.

With my limited javascript knowledge took quite some time get this working.

The problem is that I have to rewrite every single line if I want to check-hide another row.
I want to make it more usable so I can use it on similar tables without rewriting the whole thing.

Maybe I need to use a different XPath type or use some kind of changing variable?


Solution

  • Use a loop and functions. Here's one way:

    hideRowsWithLargeCellValue (
        "/html/body/div/div[2]/div/div[2]/table[2]/tbody/tr[",
        25,
        "]/td[11]",
        250
    );
    
    function hideRowsWithLargeCellValue (xpathPre, maxRows, xpathPost, maxpi) {
        for (var J = maxRows;  J >= 1;  --J) {
            var srchRez  = document.evaluate (
                xpathPre + J + xpathPost, 
                document, 
                null, 
                XPathResult.FIRST_ORDERED_NODE_TYPE, 
                null
            );
            if (srchRez.singleNodeValue  &&  srchRez.singleNodeValue.textContent > maxpi) {
                var rowToHide = srchRez.singleNodeValue.parentNode;
                rowToHide.style.display='none';
            }
        }
    }
    




    Then read "Dont Repeat Yourself" (sic).