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

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

How to transfer it

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

to that

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

@jsFiddle

I 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 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 scripts, but when the tree is really massive, the browser just freezes, is there a more efficient way to accomplish this?
I am looking for a jQuery or pure javascript solution.

+2
source share
2 answers

I would suggest:

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

JS Fiddle demo .

Literature:

+4
source

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

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

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


All Articles