Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • Why does the g that is dynamically created, hidden by default?
  • Why does $("#parent").show() work inconsistently?
  • Is there another (better) way of grouping grouping elements dynamically?
  • I am totally new to SVG, but relatively comfortable with jQuery and DOM manipulation. Is the way that I am treating SVG as just-another-tag wrong?

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

like image 325
Jugal Thakkar Avatar asked Nov 04 '22 15:11

Jugal Thakkar


1 Answers

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.

like image 161
FixMaker Avatar answered Nov 09 '22 07:11

FixMaker