How to get dynamic ID of a button in jQuery
Short Answer
Views 263
Answer:
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>
Related Articles:
This section is dedicated exclusively to Questions & Answers. For an in-depth exploration of JavaScript, click the links and dive deeper into this subject.
Join Our telegram group to ask Questions
Click below button to join our groups.