jQuery: How can I capture the ID of clicked element?

By | June 5, 2021

In some special case, if you need to capture the ID of a clicked element using jQuery code then, this tutorial is for you.

To get the ID attribute of an element, I’m going to use jQuery attr() method which helps in getting the value of any attribute created in an element.

For example, you have created a button like following and you want to get the value of ID element when someone clicks on this button.

<input type="button" class="clicks" id="mybutton" value="Click Me" />

Then, you have to write your jQuery code like this:

$('.clicks').click(function() { 
     var id = $(this).attr('id');
     alert(id);
});

In above code, I have used jQuery click() method. That will be executed when the user clicks on it.

Here is the complete code:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>capture the ID of clicked element</title>
  <style>
	#myDiv{width: 300px;border: 15px solid green;padding: 50px;margin: 20px; text-align:center;}
  </style>
</head>
<body>
	<div id="myDiv" class="abc container inner_div">
	<h4>Welcome to Lipku.com</h4>
	<input type="button" class="clicks" id="mybutton" value="Click Me" />
	</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
    $('.clicks').click(function() { 
         var id = $(this).attr('id');
         alert(id);
    });
});
	
</script>
</body>
</html>

The output will be like: