Get id from SVG objects

2

I can get the id of an SVG object through getElementById using only one.

But since I have 3 objects, how can I know the id of each one.

var shape = document.getElementById('rect1');

shape.onclick = function(){
       alert(this.id);
    };
<svg width=90% height=500px>
    <rect id="rect1" ry=0 rx=0 x=50 y=50 width=20px height=20px fill=red />
	
	<rect id="rect2" ry=0 rx=0 x=80 y=50 width=20px height=20px fill=blue />
	
	<rect id="rect3" ry=0 rx=0 x=110 y=50 width=20px height=20px fill=green />
</svg>

Fiddle: link

    
asked by anonymous 11.03.2015 / 17:01

1 answer

3

One way to do this is to use getElementsByTagName and scroll through the elements in for .

var shapes = document.getElementsByTagName('rect');

for (var i = 0; i < shapes.length; i++) {
    shapes[i].addEventListener('click', showID, false);
}
function showID(){
    alert(this.id);
}
<svg width=90% height=500px>
    <rect id="rect1" ry=0 rx=0 x=50 y=50 width=20px height=20px fill=red />
	
	<rect id="rect2" ry=0 rx=0 x=80 y=50 width=20px height=20px fill=blue />
	
	<rect id="rect3" ry=0 rx=0 x=110 y=50 width=20px height=20px fill=green />
</svg>

Fiddle

    
11.03.2015 / 17:11