How to get the id of some images with same class name

Viewed 135

In html I have some images with same class name but different ids.

<IMG STYLE="position:absolute; TOP:35px; LEFT:170px; WIDTH:25px; HEIGHT:20px; background:red;" SRC="../image_collection/xx.png" class="allBtns" id="btn1">
<IMG STYLE="position:absolute; TOP:95px; LEFT:50px; WIDTH:25px; HEIGHT:20px; background:red;" SRC="../image_collection/yy.png" class="allBtns" id="btn2">
<IMG STYLE="position:absolute; TOP:295px; LEFT:250px; WIDTH:25px; HEIGHT:20px; background:red;" SRC="../image_collection/yy.png" class="allBtns" id="btn3">
..........

If i click an image I want the ID of the image that has been clicked.

I have tried the following by it returns full list of ids:

$(".allBtns").on("click", function(event)
    {
        var ids = $('.allBtns').map(function() {
        return this.id;
        }).get();

        alert(ids);
    })

How do I get the image ID that's been clicked?

4 Answers

this refers to the current element clicked.

$(".allBtns").on("click", function(event) {
     alert(this.id); // alert the id of current element
 });

One more way is to get the id using event target:

$(document).ready(function(){
  $(".allBtns").on('click', function(e){
    console.log(e.target.id);
  })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>


<IMG STYLE="position:absolute; TOP:35px; LEFT:170px; WIDTH:25px; HEIGHT:20px; background:red;" SRC="../image_collection/xx.png" class="allBtns" id="btn1">
<IMG STYLE="position:absolute; TOP:95px; LEFT:50px; WIDTH:25px; HEIGHT:20px; background:red;" SRC="../image_collection/yy.png" class="allBtns" id="btn2">
<IMG STYLE="position:absolute; TOP:295px; LEFT:250px; WIDTH:25px; HEIGHT:20px; background:red;" SRC="../image_collection/yy.png" class="allBtns" id="btn3">

 $('.hello').click(function(){
      var id = $(this).attr('id');
      
     $('.input').val(id);
      
 });
<button class='hello'>click to get Id</button>
<button class='hello'>click to get Id</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class='hello' id='1'>click to get Id</button>
<button class='hello' id='2'>click to get Id</button>

<input class='input' type="text" />

$('.allBtns').on('click', function(e){
     console.log(this.id);
     console.log(e.target.id)
})
Related