Mari Isa Ozu
Mari Isa Ozu

Reputation: 31

How to get the "id" attribute from each <g> tag in a nested svg with javascript?

I am newbie with javascript and dealing with svg files, but I would like to get the 'id' attribute from each <g> tag in a nested svg through a javascript function depending on which g element is clicked. According to my example I want to get:
MyGroup1
MyGroup2
And how could I save the result as string variable?

Please,I would appreciate if someone could show me how to get this, as I've searched and tried everything I know to try.

<html>
<script type="text/javascript">
function(){
//What javascript code should be here?

}
</script>
<body>
<svg 
       width="200" height="200"
       style="background-color: #D2B48C; display: block; margin-bottom: 5px;"
       id="embeddedSVG">
     <g 
        id="myGroup1 onclick="function();" 
        fill="blue" 
        style="font-size: 18px; text-anchor: middle; font-family: serif;">
         <circle
              id="myCircle" 
              cx="100" cy="75" r="50"
              stroke="firebrick"
              stroke-width="3" />
         <text x="100" y="155">Hello World</text>
         <text x="100" y="175">From Embedded SVG!</text>
     </g>
<g id="MyGroup2" onclick="funciont();">
 <rect x="30" y="40" width="180" height="30" fill="#ddd" stroke="black" />
 <text x="50" y="63" font-size="18pt" fill="black">
 Display Msg</text>
</g>
   </svg>
</body>
</html>

Upvotes: 3

Views: 7933

Answers (1)

castletheperson
castletheperson

Reputation: 33476

You can pass this as a parameter to the function.

function showId(g) {
  var str = g.id;
  console.log(str);
}
#embeddedSVG {
  background-color: #D2B48C;
  display: block;
  margin-bottom: 5px;
}
#myGroup1 {
  font-size: 18px;
  text-anchor: middle;
  font-family: serif;
}
<svg width="200" height="200" id="embeddedSVG">
  <g id="myGroup1" onclick="showId(this)" fill="blue">
    <circle id="myCircle" cx="100" cy="75" r="50" stroke="firebrick" stroke-width="3" />
    <text x="100" y="155">Hello World</text>
    <text x="100" y="175">From Embedded SVG!</text>
  </g>
  <g id="MyGroup2" onclick="showId(this)">
    <rect x="30" y="40" width="180" height="30" fill="#ddd" stroke="black" />
    <text x="50" y="63" font-size="18pt" fill="black">Display Msg</text>
  </g>
</svg>

Upvotes: 4

Related Questions