Arihant Arihant - 4 months ago 10
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:

$(document).one("click",function(){
console.log(this);
}


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>
</svg>
</div>
</div>


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

Answer

To get both the element tag and its id:

$(document).click(function(event) {
    var elemTag = $(event.target).prop("tagName");
    var elemId = $(event.target).attr("id")
    alert("this is a <" + elemTag + ">. Its id is: " + elemId);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></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>
</svg>

Comments