Search code examples
jquerysvgsettingsclonejquery-svg

Keith Wood JQuery SVG: clone() followed by change() not working


In this JSFiddle, (code below), I'm simply trying to clone a path and change its settings. However when I run the code, it gives the error that rect2 does not have the method setAttribute() defined.

However, instead, when I run the change() method on rect1, it does not produce an error, as in this JSFiddle. So I suspect it's a problem with the clone method, in that it doesn't produce a complete clone.

What am I doing wrong? If it's a problem with the extension, what's a neat workaround? Thanks

$('body').svg({onLoad: function(svg){
    var path = svg.createPath();
    var rect1 = svg.path(
        path.move( 50, 50 )
        .line( 200, 0, true )
        .line( 0, 200, true )
        .line( -200, 0, true )
        .close(),
        {
            fill: 'none', 
            stroke: '#00f', 
            strokeWidth: 30
        }
    );
    var rect2 = svg.clone(null, rect1);
    svg.change(rect2, {
            fill: 'none', 
            stroke: '#f00', 
            strokeWidth: 10
    });
}});

My efforts so far:

  • If I do alert(rect1) before cloning it says "[object SVGPathElement]".
  • If I do alert(rect2) after cloning it also says "[object SVGPathElement].
  • If I do alert(rect1.setAttribute) it says "function setAttribute() {[native code]}"
  • if I do alert(rect2.setAttribute) it says "undefined".

Solution

  • The clone function returns an array of cloned nodes. So I changed

    var rect2 = svg.clone(null, rect1);
    

    to

    var rect2 = svg.clone(null, rect1)[0];
    

    What I don't get is why the returned array appears to be of type SVGPathElement!! I can't see any kind of casting in the jquery.svg.js source.