Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append a foreignObject to a SVG in Javascript

I've an SVG element with id "graphe". I want to append to this element a foreignObject which contains a paragraph. I read that it is necessary to have a "body" in this object (it's true ?). In all cases, this piece of code doesn't work :

foreign = document.createElementNS('http://www.w3.org/2000/svg', "foreignObject");
foreign.setAttributeNS('http://www.w3.org/2000/svg', 'x', 250);
foreign.setAttributeNS('http://www.w3.org/2000/svg', 'y', 100);
foreign.setAttributeNS('http://www.w3.org/2000/svg', 'width', 500);
foreign.setAttributeNS('http://www.w3.org/2000/svg', 'height', 150);

body = document.createElement("body");
body.setAttribute('xmlns', 'http://www.w3.org/1999/xhtml');

texte = document.createElement("p");
texte.textContent = "EXAMPLE";

foreign.appendChild(body);
body.appendChild(texte);
document.getElementById("graphe").appendChild(foreign);

And I don't see why. When I open the DOM Inspector in Chrome, I can see that all is here. But nothing is displayed. When I recopy DOM Inspector's code of my objects directly in the source, I see my objects on the page.

[edit] JSFiddle Demo : http://jsfiddle.net/uwZja/

like image 525
Arnaud Avatar asked Oct 27 '25 08:10

Arnaud


1 Answers

Never ever use the svg namespace for attributes in svg.

Change:

foreign.setAttributeNS('http://www.w3.org/2000/svg', ...

To:

foreign.setAttributeNS(null, ...

Or alternatively:

foreign.setAttribute("x", ...

Furthermore this part:

body.setAttribute('xmlns', 'http://www.w3.org/1999/xhtml');

is rather useless unless you want to serialize the document to a string. It has no effect, the type of element created is decided when you call createElement/createElementNS. It doesn't change.

like image 132
Erik Dahlström Avatar answered Oct 30 '25 15:10

Erik Dahlström



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!