Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to get value of namespace declaration attribute

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 Safari/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" );

like image 552
Phrogz Avatar asked Feb 19 '11 02:02

Phrogz


1 Answers

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');
like image 166
Phrogz Avatar answered Sep 29 '22 17:09

Phrogz