durilka
durilka

Reputation: 1449

Dynamically insert foreignObject into svg with jquery

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);

Upvotes: 11

Views: 5330

Answers (2)

Robert Longson
Robert Longson

Reputation: 124016

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')

Upvotes: 7

feeela
feeela

Reputation: 29932

jQuery is not well suited for SVG documents.

But you still could use plain JS in connection with jQuery:

var foreignObject = document.createElement( 'foreignobject' );

/* add further child elements and attributes to foreignObject */

document.getElementById( 'group' ).appendChild( foreignObject );

Upvotes: -1

Related Questions