3

Many of us non-jquery javaScript developers, have been using domElement.setAttribute, and its sister functions, to hack our way around countless dom elements, for all of internet eternity.

Be it, css, dom classNames, storing/retrieval of variable data, etc...

var b = document.getElementById("someDiv"); 
b.setAttribute("align", "center");

So what's the purpose / practical use of its domElement.setAttributeNS variant? This question is in regards to web browser display / uses. And not in the context of XML. In which setAttributeNS has lots of uses.

var d = document.getElementById("someDiv"); 
d.setAttributeNS("http://www.mozilla.org/ns/specialspace", "align", "center");
PicoCreator
  • 9,886
  • 7
  • 43
  • 64

2 Answers2

2

That's domElement not htmlElement.

It is useful when you are working with a DOM constructed from XML that uses elements from multiple namespaces.

(And if you want to know why namespaces are useful, then see this question)

Community
  • 1
  • 1
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • in the context of XML. That I would understand, however the example on MDN clearly uses NS, in the context of display manipulation. (2nd example). Of which i fail to grasp – PicoCreator Oct 31 '12 at 12:35
  • They're using an XML format that describes presentation for the example. There are lots of different XML formats that do that. – Quentin Oct 31 '12 at 12:38
  • Hmm, I guess... "Its meant for XML (domElement). And not htmlElement (which inherits domElement)" & "the example on MDN is just an example"... would count as an answer +_+ , . Haha – PicoCreator Oct 31 '12 at 12:49
2

In HTML Documents (i.e. Document objects create by the text/html parser) there really aren't many uses for setAttributeNS.

But if look at what the HTML5 parser is required to do when parsing foreign content (i.e. SVG abd MathML) we find this table: adjust foreign attributes.

So it automatically moves and renames some attributes into the XLink, XML and XMLNS namespaces. When you are manipulating the DOM via functions like setAttribute and setAttributeNS, that automatic moving and renaming won't happen, so to get the attributes into their correct namespaces, you need to use setAttributeNS to create and modify them.

xlink:href is possibly the most common of these to be set via setAttributeNS()

mcmimik
  • 1,389
  • 15
  • 32
Alohci
  • 78,296
  • 16
  • 112
  • 156