I am new to jQuery and I am currently trying to get id
of an element that has been clicked in the page.
As far as I have read, I know that we can get an id
of current element by using $(this).attr("id");
But I am not gettting the id
instead it says undefined
.
HTML code:
<html>
<body>
<form action="#">
<a href='#' id="1st">First</a></br>
<a href='#' id="2nd">Second</a></br>
<p id='3rd'>Test text</p>
</form>
<script type="text/javascript" src="jquery.js"> </script>
<script type="text/javascript" src="code.js"> </script>
</body>
</html>
code.js(jQuery code):
$(document).click(function(){
alert($(this).attr("id"));
});
How ever the following code returns the id perfectly:
$(document).click(function(event){
alert(event.target.id);
});
Can someone please explain why is this happening & what have I misunderstood? Thanks.