1

I have installed greasemonkey plug-in for Firefox (my FF version is 21.0). I wrote a userscript named mahesh.user.js

var links = document.evaluate("//span", document.body, null, 6, null);

Now when I print the following

console.log(links);

The Firebug debugger writes out the XPathResult object. But I am unable to use any of the XPathResult properties such as snapshotLength or methods such as iterateNext() or snapshotItem(). Nothing gets printed on the console if I do this.

i.e.

 var thisLink = links.iterateNext();

 console.log("I am here -- 111:  " + thisLink); 

  i = 0;

  while(thisLink) {
    console.log("thisLink #" + (++i));
  }

Nothing gets printed on the console except for the first "I am here".

Need help please. Kindly advice.

Regards Mahesh.

Mahesh
  • 954
  • 8
  • 18

1 Answers1

2

If you use the result type 6 then you can't iterate but you should be able to access items as follows:

for (var i = 0, l = links.snapshotLength; i < l; i++)
{
  var span = links.snapshotItem(i);
}

If that loop does not produce any result then probably as the XPath does not find any node. Reasons for that can be namespaces in the input document.

On the other hand if you simply want to find all span elements then doing document.getElementsByTagName('span') should suffice, there is no need for XPath.

As for your document.evaluate("//span", document.body, null, 6, null); call, if you make the second item a node different than the document itself, your path should be relative as in document.evaluate(".//span", document.body, null, 6, null);, otherwise the whole document is searched anyway.

Martin Honnen
  • 160,499
  • 6
  • 90
  • 110
  • I tried to test it on a simple html such as the following: This is some title we have This is span 1 This is span 2 This is span 3 console.log("before the for loop..." + links); prints out all the span and iterates using snapshotLengh. I believe iterateNext() work with this, I did not test though. But my requirement is to get the span inside a dojo widget. I thought there is no difference between a simple document with and one that is generated by DOJO. – Mahesh Sep 19 '13 at 05:52
  • I don't know which markup or element structure a Dojo widget generates, are you sure it contains `span` elements? If you need further help then consider to add a URL to a sample page, together with some explanation which data you are looking for. Or if there is a tag on Stack Overflow for Dojo, add that, maybe then someone with knowledge of its widgets and how/when they are created can tell why your code fails. – Martin Honnen Sep 19 '13 at 09:34