我需要在 DocumentFragment
上做一些 DOM 手术,我正在尝试使用 XPath 查找需要修改的节点。但是,我不知道如何获得 document.evaluate
处理一个片段。我试过
fragment.ownerDocument.evaluate(
'//*',
fragment.ownerDocument,
null,
XPathResult.ANY_TYPE,
null
)
但这没有用。
最佳答案
使用 svg
如果您需要针对 XML 运行 XPath,则作为临时元素,因为安全限制会阻止在未附加到 DOM 的元素上评估 XPath 表达式:
<!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>
或者使用 JavaScript 实现。
关于javascript - 针对 DocumentFragment 的 XPath 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18155388/