I ate some tau
I ate some tau

Reputation: 115

Select and manipulate g elements of an SVG using javascript

How can I select all paths inside a g group by class? For example

<svg>  
...  
<g  
class="myClass"  
...  
<path  
...  
/>  

in javascript, how could select all the paths inside myClass?

Upvotes: 1

Views: 6442

Answers (1)

Oriol
Oriol

Reputation: 288260

You can use usual DOM methods, like querySelector, getElementsByTagName, getElementsByClassName, ...

function randHexColor() { // Be aware it can produce invalid colors
  return '#' + (Math.random()*Math.pow(2,8*3)|0).toString(16);
}
var svg = document.getElementById('svg'),
    paths = svg.querySelectorAll('.myClass > path');
for(var i=0; i<paths.length; ++i) {
  paths[i].style.fill = randHexColor();
}
<svg id="svg" height="200" width="350">  
  <g class="myClass" transform="scale(50)" fill="orange" >
    <path d="M 1,1 3,1 2,3 Z" />
    <path d="M 4,1 6,1 5,3 Z" />
  </g>
</svg>

Upvotes: 6

Related Questions