Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using XPathResult

Tags:

xpath

I'm finding little documentation on XPathResult on the mozilla developper site. All functions listed redirect to the main page, so they're probably not documented yet.

var myFind;
myFind = document.evaluate(
    '/html/body/table[1]',
    document,
    null,
    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
    null);

I'm looking for a way to alert the HTML tree that is under the path given.

Using alert(myFind); doesn't work, it just gives "XPathResult". There's just a tbody and a bunch of tr elements beneath it, and I'd like to see them all in an alert as 1 string.

What function can myFind use to do this?

like image 872
KdgDev Avatar asked Sep 17 '10 22:09

KdgDev


1 Answers

var myFind;
myFind = document.evaluate(
    '/html/body/table[1]',
    document,
    null,
    XPathResult.FIRST_ORDERED_NODE_TYPE,
    null);

var node = myFind.singleNodeValue;

I'm using FIRST_ORDERED_NODE_TYPE because you're only looking for a single table. singleNodeValue lets you extract the node.

Now node is a regular HTML DOM Node. You can serialize it the same way as any other node, e.g. with serializeToString:

new XMLSerializer().serializeToString(node)

You may find Using XPath and XPathResult helpful.

like image 130
Matthew Flaschen Avatar answered Sep 27 '22 20:09

Matthew Flaschen