Inserting a (g) node in the middle of a tree (SVG) using jQuery

拥有回忆 提交于 2019-12-12 18:28:29

问题


What is the most recommended/efficient way to insert a node in the middle of a tree.

How to transpose this

<svg id="root" ... >
  <g id="child1">...</g>
  <text id="child2">...</text>
  <rect id="child3">...</rect>
  ...
</svg>

to this

<svg id="root" ... >
  <g id="parent">
    <g id="child1">...</g>
    <text id="child2">...</text>
    <rect id="child3">...</rect>
    ...
  </g>
</svg>

@jsFiddle

I have tried

var $parent = $("g").attr("id","parent");
var $root = $("#root");
$root.contents().each(function(){
   $child=$(this);
   $child.remove();
   $parent.append($child);
});
$root.append($parent);

I have also tried using the moveTo method in this answer

(function($){
    $.fn.moveTo = function(selector){
        return this.each(function(){
            var cl = $(this).clone();
            $(cl).appendTo(selector);
            $(this).remove();
        });
    };
})(jQuery);

$root.contents().each(function() {
    $(this).moveTo($parent);
});

All of these methods work in simple scenarios but when the tree is really massive, the browser simply hangs, is there a more efficient way to perform this?
I am looking for a jQuery or pure javascript solution.


回答1:


I'd suggest:

$('#root > div').wrapAll('<div id="parent" />');

JS Fiddle demo.

References:

  • wrapAll().



回答2:


This will make only one addition to the DOM, so this will be fast :

$('#root').html('<div id=parent>'+$('#root').html()+'</div>');


来源:https://stackoverflow.com/questions/12547194/inserting-a-g-node-in-the-middle-of-a-tree-svg-using-jquery

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