Q: How can I find out which namespace an attribute refers to in the current scope? Suppose I have an embedded svg:
<svg 
  width="5cm" 
  height="6cm"
  viewBox="0 0 5 6"
  version="1.1"
  xmlns="http://www.w3.org/2000/svg"
  xmlns:xlink="http://www.w3.org/1999/xlink"
>
...
  <a id="foo">...</a>
...
</svg>

I want to add an arbitrary attribute to #foo with .setAttributeNS(), but only given the attribute name (e.g. xlink:href) and value, not the attribute namespace.
Is there a way to look up what namespace a name belongs to? It seems like there should be because I could hard code <a xlink:href="..."> and it would resolve to the proper namespace, so there should be some scoping I can take advantage of.
For the xlink:href example, I could just traverse up the ancestors of #foo until I found the svg's xmlns:xlink attribute, and use that value for the namespace, but it seems like it should be easier.

A: The answer is in the W3 specification: use lookupNamespaceURI.

A: When using the correct namespaceURI, if the namespace already have a prefix, then the DOM implementation should use it.
var doc = (new DOMParser()).parseFromString(
    '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"/>',
    "application/xml");
doc.documentElement.setAttributeNS(
    "http://www.w3.org/1999/xlink",
    "href", "data:text/plain,yep");
console.log((new XMLSerializer()).serializeToString(doc));

>>> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="data:text/plain,yep"/>

Other than that, there is indeed no other way than to traversing the nodes somehow and figuring it out yourself.

A: Would setAttribute work? It doesn't require a namespace. 
https://developer.mozilla.org/en-US/docs/Web/API/element.setAttribute?redirectlocale=en-US&redirectslug=DOM%2Felement.setAttribute
Or you can pass null to setAttributeNS. 
