views:

62

answers:

3

I am using this in a Firefox extension and can't get it to work.

var allLinks = document.evaluate( '//a[@href]', window.document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null); window.alert(allLinks);

This alerts "[object XPathResult]". However the following always returns "0". (And there are certainly links on the page.

window.alert(allLinks.snapshotLength);
+1  A: 

If it's firefox specific and I assume you only use new versions.. can't you use querySelectorAll?

document.querySelectorAll('a[href]')

Also - are you doing it when the DOM has fully loaded? bind it to DOMContentLoaded or something.

document.addEventListener('DOMContentLoaded', fn, false);

EDIT: Your xpath works for me. Did it in the console on an existing, loaded page. Pretty sure you're querying before anything exists.

meder
A: 

The answer that you don't want to hear - "works for me".

See this example (alerts 3 for me).

What browser and what version are you testing this on?

Anurag
It's within a Firefox extension in 3.6.
Josh
A: 

This worked.

        var allLinks = top.document.getElementById("content").selectedBrowser.contentDocument.evaluate(
                            treeView.model[0].xpath, 
                            top.document.getElementById("content").selectedBrowser.contentDocument, 
                            null, 
                            XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, 
                            null);
Josh
Probably it was searching in `document` which is the document of the browser itself (i.e. the main Firefox window, `browser.xul`) not the webpage you were trying to search.
MatrixFrog
By the way you can use `gBrowser` instead of `top.document.getElementById('content')`.
MatrixFrog