Adding SVG object inside a div dynamically

1

I have an SVG element created from a clone. What I wanted was to insert this clone into a new div. I used this code.

function clone(){
        var newrect = document.getElementById('rect').cloneNode(true);
        document.getElementById("svg").appendChild(newrect);

        newrect.setAttribute("x", 100);
        newrect.setAttribute("y", 100);
        newrect.style.position = 'absolute';    


        var div = document.createElement('div');
        document.body.appendChild(div);
        div.id = 'div1';


        var div1 = document.getElementById("div1");
        div1.insertBefore(newrect, div1.firstChild);
}
    
asked by anonymous 20.10.2014 / 13:32

1 answer

1

I suggest you then change your clone function code to:

function clone() {
    var newrect = document.getElementById('svg').cloneNode(true);
    newrect.setAttribute("x", 100);
    newrect.setAttribute("y", 100);
    newrect.style.position = 'absolute';
    newrect.id = 'novoSVG';

    var div = document.createElement('div');
    div.style.height = '100px';
    div.style.width = '50px';
    addEvent(div, 'mousedown', function(e){ start_drag(div, e)});
    div.appendChild(newrect);
    document.body.appendChild(div);
}

Example: link

In the background, and seen the previous div be removed from the starting position via drag and once it gives position: absolute; to the new div, you do not need to worry about the position in the DOM. I also added a call to start_drag() to join an event handler to the new div.

    
20.10.2014 / 19:40