Jugal Thakkar
Jugal Thakkar

Reputation: 13472

Grouping SVG elements dynamically

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).

enter image description here

calling $("#parent").show(); works in sometime cases but not all

Questions:

Tried on both Firefox (15.0.1) and Chrome (21.0.1180.89) with same results

Upvotes: 5

Views: 2632

Answers (1)

FixMaker
FixMaker

Reputation: 3877

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.

Upvotes: 2

Related Questions