XPath query against DocumentFragment
Asked Answered
P

1

6

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.

Primordial answered 9/8, 2013 at 20:46 Comment(2)
Would this be a document.createDocumentFragment with DOM nodes, or is this XML, there's not really much context here ?Yak
@Yak It comes from a call to saxonica.com/ce/user-doc/1.1/#!api/xslt20processor/…Primordial
D
-2

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.

Dorr answered 8/11, 2013 at 10:25 Comment(1)
In a local tentative here, I created independently from DOM x and its child y, and I could evaluate on x using document: x=document.createElement("x");x.appendChild(document.createElement("y"));document.evaluate("y",x,null,XPathResult.ANY_UNORDERED_NODE_TYPE,null).singleNodeValue;, so the problem is not being or not attached to the DOM, it is a fragment matterCandlemaker

© 2022 - 2024 — McMap. All rights reserved.