Home / Questions / How to get dynamic ID of a button in jQuery
Explanatory Question

How to get dynamic ID of a button in jQuery

👁 322 Views
📘 Detailed Answer
🕒 Easy to Read
Read the answer carefully and go through the related questions on the right side to improve your understanding of this topic.

Answer with Explanation

I have written below code of HTML. Here id="1" , id="2", id="3", id="4" ............ id="100" dynamically created.


<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<ul class="dropdown-menu"> 
<li><button type="button" id="1" class="highlight"> Edit </button> </li>
<li><button type="button" id="2" class="highlight"> Edit </button> </li>
<li><button type="button" id="3" class="highlight"> Edit </button> </li>
<li><button type="button" id="4" class="highlight"> Edit </button> </li>
...............................

<li><button type="button" id="100" class="highlight"> Edit </button> </li>
</ul>

Way 1: you can use this jQuery code.

In this case we are targeting the class highlight and then taking the id using attr() function.

I have written below code of HTML.


<script type="text/javascript"> 

$(document).ready(function() {  
$('.highlight').on('click', function(e){
     var id = $(this).attr('id');
     alert(id); 
});
});

</script>

Way 2: Below Code also works Fine

In this process I am directly targeting the class and taking its id.

I have written below code of HTML.


<script type="text/javascript"> 

$(document).ready(function() {  
 
$(document).on("click", ".highlight", function() {
  var id =  this.id; 
  alert(id); 
});

});

</script>