Grouping SVG Elements Dynamically

I am trying to dynamically wrap some svg elements, such as rect , text , etc., in one g using javascript (jQuery)

This is what svg looks like initially

 <div id="container"> <svg ...> <rect .../> <circle .../> <text ...>...</text> </svg> </div> 

the script (based on the helpful answers that I got @ Insert (g) node in the middle of the tree (SVG) using jQuery ) which I use to insert into the g tag.

 $("#container svg > *").wrapAll('<g id="parent" />'); 

The converted svg as follows:

 <div id="container"> <g id="parent"> <svg ...> <rect .../> <circle .../> <text ...>...</text> </svg> </g> </div> 

But nothing is displayed in the user interface. Even firebug indicates that g will not be available (for example, for hidden elements).

enter image description here

call $("#parent").show(); works once , but not all

Questions:

  • Why is the created g dynamically created hidden by default?
  • Why does $("#parent").show() work inconsistently?
  • Is there any other (better) way to group grouping elements dynamically?
  • I am completely new to SVG, but relatively comfortable with jQuery and DOM manipulations. Is the way I treat SVG as a wrong error?

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

+4
source share
1 answer

I believe the reason is because SVG is actually inside another namespace for containing HTML. When you pass the HTML fragment to jQuery ( <g id="parent" /> in your case), it is created in the namespace of the HTML document, not in the SVG.

JQuery is really not suitable for creating and managing elements other than HTML, although you could get your home halfway 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 previously used jQuery to successfully manage SVG elements with the Great JQuery Plugin for Keith Wood . You can take a look at that.

This answer discusses SVG and HTML namespaces in more detail.

+2
source

Source: https://habr.com/ru/post/1435699/


All Articles