Wrap existing SVG elements in G tag

亡梦爱人 提交于 2021-02-07 12:55:20

问题


This seems like it'd be a simple question to answer but I'm having a hard time doing so: Is it possible to "wrap" existing SVG shapes in a new SVG g tag (i.e. group) using d3.js, the way .wrap() works in jQuery? If I were to simply create a new g tag "manually", how would I then go about moving an existing element into that g?


回答1:


If you pass an existing DOM element to append or insert, the element (and it's children) will be moved from their current place in the DOM hierarchy to wherever you've just inserted 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

});

It's a little messy because d3 expects you to always use functions to determine which element to insert or insert before, and that's not necessary when we're doing it all within an each statement. But it should get the job done!

(Or, use the JQuery method if you've already got the library on your page. JQuery doesn't usually have any problem manipulating SVG elements, it just can't create them!)




回答2:


Unable to make @AmeliaBR 's answer to work, I solved the problem like so

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



来源:https://stackoverflow.com/questions/22704176/wrap-existing-svg-elements-in-g-tag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!