How to get the id of the element clicked using jQuery?

Total Post:3

Points:21
JQuery 
 1018  View(s)
Ratings:
Rate this:
<div class="main_div">
    <div id="inner_div">   
        <span id="d1" class="get_clicked">click to get id</span>
    </div>
</div>

 

 

How to get the id of the clicked element? 

The span which is present inside the inner_div will be having different ids because I will be loading the span from the model(MVC) using jquery ajax. So there will be 'n' number of span. All the span will have unique id. I want to get the id of the span which I click.

How to get the id of the span when clicked? How to do this using jQuery?

  1. Post:27

    Points:189
    Re: How to get the id of the element clicked using jQuery?

     This code will help you surely....

    $(document).on('click', 'span', function () {
                    alert(this.id);
                });
     
                or you can use .on
     
                $('span').on('click', function () {
                    alert(this.id);
                });
     

      Modified On Apr-11-2018 10:56:35 PM
  1. Post:1

    Points:7
    Re: How to get the id of the element clicked using jQuery?

    Since you are loading in the spans via ajax you will have to attach delegate handlers to the events to catch them as they bubble up.


    $(document).on('click','span',function(e){
        console.log(e.target.id)
    })
    you will want to attach the event to the closest static member you can to increase efficiency.
    $('#main_div').on('click','span',function(e){
        console.log(e.target.id)
    })

     is better than binding to the document for instance.

    This question may help you understand




      Modified On Apr-11-2018 10:56:58 PM

Answer