XPath query against DocumentFragment

1.1k Views Asked by At

I need to do some DOM surgery on a DocumentFragment, and I'm trying to use XPath to find the nodes that need to be modified. However, I can't figure out how to get document.evaluate to work on a fragment. I tried

fragment.ownerDocument.evaluate(
    '//*',
    fragment.ownerDocument,
    null,
    XPathResult.ANY_TYPE,
    null
)

but that did not work.

1

There are 1 best solutions below

1
On

Use an svg as a temp element if you need to run XPath against XML, since security restrictions prevent evaluating XPath expressions on an element not attached to the DOM:

<!DOCTYPE HTML>
<html lang="en">
<head>
<title>XPath Context</title>
<meta charset="utf-8">
</head>
<body>

<svg id="model" version="1.1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"">
  <?foo bar?>
</svg>

<script type="text/javascript;version=1.7">
function $xpath(aXPath, aContext)
  {
    let nodes = [];
    aContext = document.getElementById("model") || doc;
    let results = document.evaluate(aXPath, aContext, null, XPathResult.ANY_TYPE, null);
    let node;

    while ((node = results.iterateNext())) {
      nodes.push(node);
    }

    return nodes;
  }
</script>
</body>
</html>

Or use a JavaScript implementation.