如何使用document.evaluate查询svg元素?

时间:2015-11-15 11:18:20

标签: javascript xpath svg

我的文档包含div元素,其中包含svg元素。

当我查询div元素时,我得到的返回值甚至显示svg子元素。

$x('//div')
[<div class=​"schema">​…​</div>​, <div class=​"relations">​<svg class=​"relations">​…​</svg>​</div>​]

但是当我查询svg元素时,我没有得到任何结果。

$x('//svg')
[]

我不知道为什么。我在Chromium 45.0.2454.85中做到了这一点。

有人能解释一下这里发生了什么吗?

1 个答案:

答案 0 :(得分:1)

SVG元素位于SVG名称空间http://www.w3.org/2000/svg中,如果使用evaluate DOM方法,则可以将名称空间解析器作为第三个参数传递:

function setFill(xpath, color) {
  var el = document.evaluate(xpath, document, function(prefix) { if (prefix === 'svg') { return 'http://www.w3.org/2000/svg'; }}, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
  if (el !== null) {
    el.setAttribute('fill', color);
  }
}
<div>
  <svg width="200" height="200">
    <circle cx="100" cy="100" r="50" fill="green"/>
  </svg>
  <input type="button" value="red" onclick="setFill('//svg:circle', 'red');">
</div>

我不知道开发人员工具中的$x函数是否允许类似的东西。