Link to home
Start Free TrialLog in
Avatar of 93jordanaj
93jordanajFlag for United Kingdom of Great Britain and Northern Ireland

asked on

How do I use the jQuery click function to get the ID of a parent if a child is clicked?

I have an SVG with grouped elements. The parent group <g> has an ID. When the parent or any children are clicked I want this ID to be passed to the script.

I have the following which works perfectly if the parent with the ID is clicked, but not if any children are clicked. How should I modify the script so that if the parent or any children are clicked the parent ID is used?

	var id ='-')[1]

Open in new window

Snippet from the SVG:

<g class="room" id="room-120">
	<polyline fill="#B0DED6" points="366.3,151.2 366.3,206.9 314.4,206.9 314.4,151.2 332.2,151.2 334.2,151.2 366.3,151.2 	"/>
		<path fill="#00AA8F" d="M329.5,170.3l-1.4,0.3l-0.4-1.4l2.3-0.7h1.2v8.1h-1.7V170.3z"/>
		<path fill="#00AA8F" d="M335.7,170.3l-1.4,0.3l-0.4-1.4l2.3-0.7h1.2v8.1h-1.7V170.3z"/>
		<path fill="#00AA8F" d="M343.6,168.5h1.6l3.4,8.1h-1.8l-0.7-1.8h-3.4l-0.7,1.8h-1.8L343.6,168.5z M345.4,173.2l-1.1-2.6l-1.1,2.6
<g class="room" id="room-121">
		<path fill="#1D1D1B" d="M328.5,190.6h1.9v-6.1c-0.3,0.1-0.7,0.2-1.1,0.2c-0.3,0-0.6,0-0.8-0.1V184c1,0,1.9-0.4,2.3-1h0.7v7.6h1.8
		<path fill="#1D1D1B" d="M337.1,187.6c1.3-0.8,2-1.4,2-2.5c0-1-0.6-1.7-1.7-1.7c-0.8,0-1.4,0.4-1.7,0.9c0.4,0.1,0.6,0.4,0.6,0.8

Open in new window

I appreciate this is last thing on a Friday (UK time) but this is quite urgent for a deadline early next week so I'll be working on this over the weekend. Any help would be really appreciated.

Avatar of Md Shah
Md Shah
Flag of India image

Link to home
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Or You can also try..


	var id = '';	

		id = $(this).attr('id'); 
		id = $(this).closest(''id');
	id = id.split('-')[1];


Open in new window

Avatar of 93jordanaj


Fantastic, thank you so much! Such a quick reply and works perfectly. For anyone else who may use this, I had to add in a missing quote after the "", but this made it work as needed. Thank you.
Thanks for the second example. Is one any better than the other? If so I'd be happy to go with your recommendation, otherwise the first works exactly as needed.
Any time...

Happy I was helpful...!!!

Good Luck with your deadline next week :-)
Nothing much... Its just beauty of JQuery to provide multiple ways for a single issue ;-)