ある要素の子要素全てにアクセスする方法(SVG)

SVGでいくつかの要素をgタグでグループ化しているとき、getElementById()でgタグの要素を取得して、その子要素全てにアクセスする例。

childNodesで子ノードが取得できる。ノードにはテキストノード(text要素ではない)が含まれるので、nodeNameでノードの種類をチェックした上で処理を行う。

<?xml version="1.0" encoding="utf-8"?>
<svg xmlns="http://www.w3.org/2000/svg"
     xmlns:xlink="http://www.w3.org/1999/xlink"
	width="800" height="800"
     version="1.0" onload="init()">
<script type="text/javascript">
<![CDATA[
function init(){
	var group1 = document.getElementById("group1");
	var children = group1.childNodes;
	for(i=0;i<children.length;i++){
		if(children[i].nodeName=='circle'){
			children[i].style.setProperty('fill', '#00ff00');
		}
	}
}
]]>
</script>
<g id="group1">
	<circle cx="100" cy="100" r="50" style="fill: #ff0000" />
	<circle cx="200" cy="100" r="50" style="fill: #ff0000" />
	<circle cx="300" cy="100" r="50" style="fill: #ff0000" />
	<circle cx="400" cy="100" r="50" style="fill: #ff0000" />
</g>
<g id="group2">
	<circle cx="100" cy="200" r="50" style="fill: #ff0000" />
	<circle cx="200" cy="200" r="50" style="fill: #ff0000" />
	<circle cx="300" cy="200" r="50" style="fill: #ff0000" />
	<circle cx="400" cy="200" r="50" style="fill: #ff0000" />
</g>
</svg>