在Javascript中将foreignObject附加到SVG

在Javascript中将foreignObject附加到SVG,javascript,dom,svg,Javascript,Dom,Svg,我有一个id为“graph”的SVG元素。我想在这个元素后面附加一个foreignObject,它包含一个段落。我读到有必要在这个物体中有一个“身体”(是真的吗?)。在所有情况下,这段代码都不起作用: foreign = document.createElementNS('http://www.w3.org/2000/svg', "foreignObject"); foreign.setAttributeNS('http://www.w3.org/2000/svg', 'x', 250); fo

我有一个id为“graph”的SVG元素。我想在这个元素后面附加一个foreignObject,它包含一个段落。我读到有必要在这个物体中有一个“身体”(是真的吗?)。在所有情况下,这段代码都不起作用:

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);
我不明白为什么。当我在Chrome中打开DOM检查器时,我可以看到所有内容都在这里。但是什么也没有显示。当我直接在源代码中复制DOM Inspector的对象代码时,我会在页面上看到我的对象


[编辑]JSFIDLE演示:

永远不要将svg名称空间用于svg中的属性

更改:

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

或者:

foreign.setAttribute("x", ...
此外,本部分:

body.setAttribute('xmlns', 'http://www.w3.org/1999/xhtml');
除非您想将文档序列化为字符串,否则它是非常无用的。它不起作用,创建的元素类型在调用
createElement/createElementNS
时确定。它不会改变

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