Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically insert foreignObject into svg with jquery

Tags:

jquery

svg

Given this html+svg

<div id="svg" style="width: 300px; height: 300px">
    <svg xmlns="http://www.w3.org/2000/svg"  width="300" height="300">
        <svg x='10' y='10' id='group'>
           <rect id="rect" x='0' y='0' width='100' height='100'  fill='#f0f0f0'/>
        </svg>
        <svg x='100' y='100' id='group2'>
           <rect id="rect2" x='0' y='0' width='100' height='100' fill='#f00000'/>
           <foreignobject x='0' y='0' width='100' height='100' >
                <body>
                    <div>manual</div>
                </body>
           </foreignobject>
        </svg>
    </svg>
</div>

I'd like to insert a foreignObject into #group (preferably with jquery for it makes manipulation simpler). I've tried(code is sketchy from head)

$("#group").append("<foreignobject x='0' y='0' width='100' height='100'><body><div>auto</div></body></foreignobject>") 

to no avail probably because "body" gets stripped. I've tried several exotic ways of creating the body element and the best I could - firebug doesn't grey out the inserted foreignObject element anymore but it's still not visible.

So either I'm not seeing something obvious or there's a strange way to do that.

Ideas?

Update with final solution This is the shortest of what I came up with

var foreignObject = document.createElementNS('http://www.w3.org/2000/svg', 'foreignObject' );
var body = document.createElement( 'body' ); // you cannot create bodies with .apend("<body />") for some reason
$(foreignObject).attr("x", 0).attr("y", 0).attr("width", 100).attr("height", 100).append(body);
$(body).append("<div>real auto</div>");
$("#group").append(foreignObject);
like image 281
durilka Avatar asked Sep 17 '12 15:09

durilka


1 Answers

SVG is case sensitive and the element name you want is called foreignObject. To create it using the dom you would call

document.createElementNS('http://www.w3.org/2000/svg', 'foreignObject')
like image 153
Robert Longson Avatar answered Nov 06 '22 13:11

Robert Longson