开发者

Correct way to get value of namespace declaration attribute

开发者 https://www.devze.com 2023-02-11 04:56 出处:网络
Consider this SVG/XML and JavaScript: <svg id=\"foo\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\">

Consider this SVG/XML and JavaScript:

<svg id="foo" xmlns="http://www.w3.org/2000/svg"
              xmlns:xlink="http://www.w3.org/1999/xlink">
  <use id="bar" xlink:href="#whee" />
</svg>
...
var foo  = document.getElementById('foo');
var bar  = document.getElementById('bar');
var xlnk = foo...; // What is correct here?
var link = bar.getAttributeNS(xlnk,'href');

Clearly I can make this work with xlnk = "http://www.w3.org/1999/xlink"; my question, however, is what is the correct way to dynamically fetch the xmlns:xlink attribute on the svg element?

The following code happens to work in Safa开发者_开发问答ri/Chrome/FF, but is it really valid?

var xlnk = foo.getAttribute('xmlns:xlink');

The following code returns an empty string in those browsers:

var xlnk = foo.getAttributeNS( "http://www.w3.org/2000/svg", "xlink" );


The getAttributeNS() specification documents the second parameter as:

"The local name of the attribute to retrieve."

Per Namespaces in XML, 3rd Edition the xmlns prefix is reserved and used as part of the PrefixedAttName to define an NSAttName.

Since a NSAttName does not have a "local part"—and a QName does—it seems that xmlns:xlink is not considered a namespace+local name, but is rather the attribute name itself. As this is consistent with the experimental results across normally-standards-compliant browsers, I am convinced that the following code is valid and correct:

var xlnk = foo.getAttribute('xmlns:xlink');
0

精彩评论

暂无评论...
验证码 换一张
取 消