Self closing nature is defined by the namespace, so it will depend heavily on how you are viewing the output of your code. From the perspective of the Dom there isn't any attribute — on a node — that specifies "auto-closing". So if you think about it, this can only be applied when rendering the Dom to a string output, and has to be decided by the renderer.
If you use your modern browser's inspector to view an SVG Element (with correct namespace) you will see that the circle items are displayed as auto-closed. However, with the same set-up (but with incorrect namespace) — not only will your SVG not render — you will see the inspector treats it as HTML. In HTML there is no specification for circle
so it will just fallback to the default. Which is properly closed.
correct namespacing
var body = jQuery('body'),
svg = jQuery(document.createElementNS('http://www.w3.org/2000/svg', 'svg')),
cir = jQuery(document.createElementNS('http://www.w3.org/2000/svg', 'circle'));
cir.attr({cx: 30, cy: 30, r: 20, style: 'fill: red;'});
svg.attr({
viewBox: "0 0 120 120",
version: "1.1",
xmlns: "http://www.w3.org/2000/svg"
});
svg.appendTo(body);
svg.append(cir);
incorrect namespacing
var body = jQuery('body'),
svg = jQuery('<svg>'),
cir = jQuery('<circle>');
cir.attr({cx: 30, cy: 30, r: 20, style: 'fill: red;'});
svg.attr({
viewBox: "0 0 120 120",
version: "1.1"
});
svg.appendTo(body);
svg.append(cir);
No matter how you set up your Dom however, I can bet you are using some function or attribute that mentions "html" to view the source of your construction. I have found that no matter how well I build my SVG (with correct namespaces), if I use .innerHTML
(or jQuery's .html()
which is basically the same) the result will be with proper closing tags. That is because you are asking the browser to render it as HTML, so you get the same problem.
I have confirmed the above even using D3 to set up the structure.
console.log(svg.get(0).innerHTML); // <circle></circle>
What you need is .innerSVG
or something similar.
The overall question should be however — what are you actually attempting to do. If it is to build something that exports SVG Source correctly, then this might be desired — but I can't think of another reason. Closed or auto-closed makes no difference to the behaviour of the markup itself.