How to wrap a set of svg elements with a <g> tag?
One way is to add the g element and add other elements to it.
$("path").click(function() { var $svg = $("#mysvg"); // #mysvg is SVG doc var g = document.createElementNS('http://www.w3.org/2000/svg', 'g'); g.setAttribute("id", "g"); $svg.append($(g)); $svg.find("path").each(function() { $(this).css("stroke", "red").appendTo($(g)); }); $("#cont").html($svg); // #cont is svg "container", eg. div }); Working example: http://jsbin.com/ayulaq/2
It uses jQuery to simplify DOM operations. I used this method to add all the children in the SVG to the same parent group in order to simplify (and speed up) the determination of the actual frame size for all elements. Sometimes SVG documents do not explain the width and height of the root element of the SVG, or it’s wrong, and to resize the SVG document (or to resize the newly created g-element [and as long as all its children] correspond to the SVG document), we need to get a bbox that covers all the elements. After the above code, we can call $("#g")[0].getBBox() to get the size of all the elements in the SVG document. There is also this way if size matters only: var setti = p.set(); setti.push(path1,path2); console.log(setti.getBBox()); var setti = p.set(); setti.push(path1,path2); console.log(setti.getBBox()); but set not suitable in all cases.
This technology also applies to drag and drop to speed up the drag and drop of large sets of items. Instead of using the Raphael set , which changes the transform attribute of each object in a separate set, using g instead, it’s enough to modify the g attribute to transform the element.
Attention, of course, only refers to the fact that Raphael uses the SVG backend.