TL;DR Summary: Is it proper to use setAttribute
instead of setAttributeNS
for SVG elements?
Details:
Consider this SVG image embedded in XHTML5 that uses JavaScript to dynamically create and add elements to the drawing: http://phrogz.net/svg/svg_in_xhtml5.xhtml
The SVG elements created by JavaScript and appended to the <svg>
element must be created using...
var el = document.createElementNS("http://www.w3.org/2000/svg",'foo');
...instead of...
var el = document.createElement('foo');
...in order for them to be treated as SVG elements and rendered in the browser. This is reasonable and understandable. However, according to this page I should also be setting the attributes of these elements using...
el.setAttributeNS( null, 'foo', 'bar' );
...instead of the code I'm using currently:
el.setAttribute( 'foo', 'bar' );
What I am doing works in Chrome, Safari, and Firefox. Is what I have legal code—is it equivalent to the recommendation—or does it just happen to work due to the permissive nature of browsers and I must instead use setAttributeNS
to be valid?
As long as you don't use namespaced attributes (with or without a prefix) you can use setAttribute.
The setAttributeNS recommendation is good in a way, because then you don't need to worry about using different methods (and when to use which one). You really only need setAttributeNS when you need to change e.g xlink:href or custom namespaced attributes. On the other hand people do get the namespaces wrong (sometimes trying to use e.g the svg namespace instead of NULL for svg attributes), so it's not clear what is less confusing IMHO.
DOM 2 Core says this about the DOM Level 1 get/setAttribute methods:
I might add that "at the same time" should maybe have read "at the same time on the same (intended) attribute", or something similar.
SVG itself doesn't require your scripts to "be legal" or anything like that except for the svg markup itself, but it does require support for certain DOM specifications, such as DOM 2 Core in the case of SVG 1.1.