Arihant Arihant - 10 months ago 41
jQuery Question

Select element when clicked on it jquery

How can I get attribute 'id' of an element when clicked on it using jquery or simple javascript. I tried:


It logs the complete document object which makes sense as I am using document with selector, But how do I get the id of the element when I click on it. The element can be SVG or PATH or a DIV.

Sample HTML

<div id="main">
<div id="middle">
<svg id="main_svg">
<path>// code for path</path>
<svg><rect>//code for rect</rect></svg>

I want id of the element which is inside the "main_svg" SVG tag when I click on it.


To get both the element tag and its id:

$(document).click(function(event) {
    var elemTag = $("tagName");
    var elemId = $("id")
    alert("this is a <" + elemTag + ">. Its id is: " + elemId);
<script src=""></script>
<svg id="mySvg" width="400" height="400">
<rect id="myRectangle" width="300" height="100" style="fill:rgb(0,0,255)"></rect>
<path id="myPath" d="M150 0 L75 200 L225 200 Z"></path>