Search code examples
javascriptjquerysvgjquery-svg

SVG and cross reference with javascript/jQuery


Imagine this situation:

<svg height="0px">
    <defs>
        <g id="img">
            <circle id="cir1" cx="10" cy="10" r="5"/>
            <circle id="cir2" cx="30" cy="10" r="5" />
            <rect id="rect1" x="50" y="5" width="20" height="10" />
        </g>
    </defs>
</svg>
<div id="div1">
    <div id="div2" style="width:100px; height: 50px; border: 1px solid black">
        hey
    </div>
</div>
<svg height="20px"><use id="img1" xlink:href="#img"/></svg>
<svg height="20px"><use id="img2" xlink:href="#img"/></svg>
<svg height="20px"><use id="img3" xlink:href="#img"/></svg>
<svg height="20px">
    <circle id="cir5" cx="10" cy="10" r="5"/>
</svg>

It's possible to change the color ONLY of the first circle of the image with id=img1 using jQuery/javascript?

Something like

$("#img1 #cir1").css("fill","red");

I tried but it doesn't work. If can be helpful here's the fiddle: http://jsfiddle.net/MaxMarkson/q6Wep/


Solution

  • That's not possible. Think of the <use> as being paint the referenced item here. If you alter the referenced item then all the <use> instances will change.

    The authors of the SVG specification have noticed that people often want to do this sort of thing and there is a SVG parameterisation proposal which may become part of SVG 2. The examples in the parameterisation proposal are created using javascript so you could do it that way right now if you copy the mechanism there.