Karol Selak Karol Selak - 4 years ago 85
Javascript Question

<image> in SVG: static image is visible, but dynamic is not

I have two monkeys in my code: first one is static (written in SVG tag) and it's ok, but second one (generated with JS) isn't visible, although code of both in tag are quite the same after running. How is it possible? How can I fix it?

<svg version="1.1" xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">

<image xlink:href="http://6962mnpm.blox.pl/resource/118392wtf.jpg"
height="250px" width="250px" x="100px"></image>

</svg>

<script>
var test = document.createElementNS("http://www.w3.org/2000/svg", "image");
test.setAttribute("xlink:href",
"http://6962mnpm.blox.pl/resource/118392wtf.jpg");
test.setAttribute("height", "250px");
test.setAttribute("width", "250px");
test.setAttribute("x", "400px");
document.querySelector("svg").appendChild(test);
</script>

Answer Source

You can't use setAttribute to add a namespaced attribute, even though it looks right in an inspector. Instead use setAttributeNS, as:

setAttributeNS('http://www.w3.org/1999/xlink','href','http://6962mnpm.blox.pl/resource/118392wtf.jpg');

Now the monkey should render properly.

var SVGDaddy = "http://www.w3.org/2000/svg";
var TESTOBRAZKA = document.createElementNS(SVGDaddy, "image");
with(TESTOBRAZKA) {
    setAttributeNS('http://www.w3.org/1999/xlink','href','http://6962mnpm.blox.pl/resource/118392wtf.jpg');
    setAttribute("height", "250px");
    setAttribute("width", "250px");
    setAttribute("x", "100px");
}
document.querySelector("svg").appendChild(TESTOBRAZKA);

Demo: http://jsfiddle.net/Palpatim/kGy5d/

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download