Search code examples
javascriptgreasemonkeydocument.evaluate

Merging XPathResults from document.evaluate


I'm doing a bunch of document.evaluate then iterating through each result with a for loop on result.snapshotLength.

Since I do the same thing inside each loop (a thisDiv.parentNode.removeChild) I would like to do just one loop.

I've read that :

The fifth parameter can be used to merge the results of two XPath queries. Pass in the result of a previous call to document.evaluate, and it will return the combined results of both queries

So I tried :

comDivs = document.evaluate(
    "//div[@class='class name 1']",
    document,
    null,
    XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,
    null);

ggDivs = document.evaluate(
    "//div[@class='class name 2']",
    document,
    null,
    XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,
    comDivs);

But this doesn't work (although I don't have an error log, it just doesn't work).

What's the proper way of doing that? Can I run different XPath queries and merge the results? Or is there a way to pass regular expressions or some kind of alternation to the query itself?

The code I have for now is at : http://userscripts.org/scripts/review/58939

Thanks for your help !


Solution

  • You can simplify your XPath in the userscript and join single expressions with "|":

    "//div[@class='reactionsCom reactionsNiv1 first'] | " + 
    "//div[@class='googleBanner'] | " + 
    "//div[@class='blocE1B-16b'] | " +
    "//div[@class='blocE1B-16b clear']"
    

    or even better in one expression with severel conditions:

    "//div[@class='reactionsCom reactionsNiv1 first' or " +
          "@class='googleBanner' or " +
          "@class='blocE1B-16b' or " +
          "@class='blocE1B-16b clear']"
    

    As for your example above, iirc the second query would only find matches, if the result f the first query contained them, i.e. if //div[@class='class name 2'] where children of the result nodes from the first query //div[@class='class name 2'].