Wrap existing SVG elements in a G tag

This seems like a simple question to answer, but it’s hard for me to do this: is it possible to β€œwrap” existing SVG forms in a new SVG g tag (ie a group) using d3.js, the .wrap() method works in jQuery? If I just created a new g-tag "manually", how would I then move an existing element to this g?

+6
source share
2 answers

If you pass an existing DOM element to append or insert , the element (and its children) will be moved from their current location in the DOM hierarchy to where you just pasted them.

 var stuffToBeWrapped = d3.selectAll(".stuff"); stuffToBeWrapped.each(function() { d3.select( this.parentNode ).insert("g", function(){return this;} ) //insert a new <g> element immediately before this element .attr("class", "wrapper") //set anything you want to on the <g> .append( function(){return this;} ); //move the content element into the group }); 

This is a bit messy because d3 expects you to always use functions to determine which item to insert or insert earlier, and that this is not necessary when we do all this in each statement. But he has to do his job!

(Or use the jQuery method if you already have a library on your page. JQuery usually has no problems managing SVG elements, they just can't create them!)

+9
source

Unable to get @AmeliaBR to respond to work, I solved the problem as follows

 d3.selectAll(selectElementsToWrap).each(function() { var el = this; d3.select(el.parentNode) .insert("g") .attr("class", "wrapped") .append(function() { return el; }); }); 

The approved solution gave me DOMException: Failed to execute 'appendChild' on 'Node': The new child element contains the parent

+1
source

All Articles