Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the id of the element clicked using jQuery

Tags:

jquery

click

<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 the get the id of the span when clicked? How to do this using jQuery?

like image 333
Gourav Avatar asked Sep 08 '13 05:09

Gourav


People also ask

How do I get the ID of clicked element?

One way to let us get the ID of the element when we click on an element is to set the onclick property of each element object to the same click event handler function. document. getElementById('1').

How can I get the ID of an element using jQuery?

The jQuery #id selector uses the id attribute of an HTML tag to find the specific element. An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.

How do I find my e Target ID?

To get the attribute of a target element in JavaScript you would simply use: e. target. getAttribute('id');


2 Answers

update as you loading contents dynamically so you use.

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

old code

$('span').click(function(){
    alert(this.id);
});

or you can use .on

$('span').on('click', function () {
    alert(this.id);
});

this refers to current span element clicked

this.id will give the id of the current span clicked

like image 80
Tushar Gupta - curioustushar Avatar answered Oct 18 '22 19:10

Tushar Gupta - curioustushar


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

Direct vs. Delegated - jQuery .on()

like image 20
DGS Avatar answered Oct 18 '22 19:10

DGS