How can I access the subpoints of the <svg: use> tag from javascript?

I have the following SVG code in an XHTML page

<svg:svg>
<svg:svg width="450" heigth="450" viewBox="0 0 500 500">  
    <svg:defs>
        <svg:g id='mygroup'>
            <svg:circle id='a' cx="15" cy="15" r='15' fill="green" fill-opacity="0.3"/>
            <svg:line id='b' x1="15" y1="15" x2="15" y2="0" style="stroke: black;" />
        </svg:g>
</svg:defs>

<svg:rect width="400" height="400" fill="white" stroke="black" />
<svg:use id="g1" xlink:href="#mygroup" x="100" y="100" onclick="moveMe()" />
<svg:use id="g2" xlink:href="#mygroup" x="100" y="200" />
</svg:svg>

      

and I would like to change it with the following javascript code

<script><![CDATA[
    function moveMe(){
    obj = document.getElementById("g1");
    obj.setAttributeNS(null, "x", "200"); //Ok it works

    //How can I change the color of the a circle in g1? 
    obj = document.getElementById("g1.a");
    obj.setAttributeNS(null, "fill", "red"); //It doesn't work
    }
 ]]></script>

      

How do I change the color of the circle "a" in "g1"? How can I access it from my javascript code?

EDIT: If I have a second mygroup element called g2, I don't want to change its color.

+2


source to share


3 answers


A simple solution is to pass the color using the currentColor keyword like this:

<svg:svg>
<svg:svg width="450" heigth="450" viewBox="0 0 500 500">  
<svg:defs>
    <svg:g id='mygroup'>
        <svg:circle id='a' cx="15" cy="15" r='15' fill="currentColor" fill-opacity="0.3"/>
        <svg:line id='b' x1="15" y1="15" x2="15" y2="0" style="stroke: black;" />
    </svg:g>
</svg:defs>

<svg:rect width="400" height="400" fill="white" stroke="black" />
<svg:use id="g1" xlink:href="#mygroup" x="100" y="100" onclick="moveMe()" color="green"/>
<svg:use id="g2" xlink:href="#mygroup" x="100" y="200" color="blue"/>
</svg:svg>

      



If you want to change the colors, now you can simply change the "color" attribute on the "use" elements. Or just use CSS for this, like:

<style>
#g1:hover { color: lime }
</style>

      

+1


source


Replace

obj = document.getElementById("g1.a");

      

from

obj = document.getElementById("a");

      



since the id of the circle element is a and not g1.a.

iN document.getElementById (id)

id is a case-sensitive string representing the unique ID of the element 
being sought. 

      

+1


source


You can achieve the desired behavior with css.

Add this to your html-head:

<style type="text/css">
   .g1red #a {fill:red}
</style>

      

use this script code:

<script><![CDATA[
function moveMe(){
obj = document.getElementById("g1");
obj.setAttributeNS(null, "x", "200");
obj.setAttributeNS(null, "class", "g1red");  
}
]]></script>

      

0


source







All Articles