I am trying to dynamically wrap certain svg
elements like rect
,text
,etc into a single g
using javascript (jQuery)
This is how the svg looks initially
<div id="container">
<svg ...>
<rect .../>
<circle .../>
<text ...>...</text>
</svg>
</div>
The script (based on the helpful answers I received @ Inserting a (g) node in the middle of a tree (SVG) using jQuery) that I use to wrap into the g
tag.
$("#container svg > *").wrapAll('<g id="parent" />');
The transformed svg
looks like this
<div id="container">
<g id="parent">
<svg ...>
<rect .../>
<circle .../>
<text ...>...</text>
</svg>
</g>
</div>
But nothing shows up on the UI. Even firebug shows the g
to be grayed out (like it does for hidden elements).
calling $("#parent").show();
works in sometime cases but not all
Questions:
g
that is dynamically created, hidden by default?$("#parent").show()
work inconsistently?Tried on both Firefox (15.0.1) and Chrome (21.0.1180.89) with same results
I believe the reason is due to the fact that the SVG is actually resides inside a different namespace to the containing HTML. When you pass a HTML fragment to JQuery (<g id="parent" />
in your case) it is created in the namespace of the HTML document and not the SVG.
JQuery isn't really suited to creating and manipulating non-HTML elements, although you could achieve a half-way house by using a combination of native JavaScript + JQuery:
$("#btn").click(function() {
var el = document.createElementNS('http://www.w3.org/2000/svg', 'g');
var $el = $(el);
$el.attr('id', 'parent');
$("#container svg > *").wrapAll($el);
});
I've previously used JQuery to successfully manipulate SVG elements using Keith Wood's excellent JQuery plugin. You may want to take a look at that.
This answer discusses SVG and HTML namespaces in more detail.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With