Get SVG object id

Asked

Viewed 36 times

2

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

But since I have three objects, how can I know id of each.

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: http://jsfiddle.net/zr1gzL5f/

1 answer

3


One way to do this is to use getElementsByTagName and traverse the elements in a 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.