1

I have an html like this

<div class='click' id='1'>
one
<div class='click' id='2'>
    two
    <div class='click' id='3'>
        three
        <div class='click' id='4'>
            four
            <div class='click' id='5'>
                five
            </div>
        </div>
    </div>
</div>

if i have and click event on class click ,there is any way to return the id of which i click such as $('.click').click(function(){ alert('id whitch i click')

}); Becase if i click on three i allway get the id of one and two three.

Khoa Trumcuoi
  • 33
  • 1
  • 5

4 Answers4

3

Sure, just do this:

$('.click').click(function(e){ //e=event
    alert($(this).attr("id")); // alert clicked element's id
    e.stopPropagation(); // stop event propagation so it doesnt propagate to click 1 and click 2
})

Update: As mentioned by Felix Kling, you can access de DOM directly and use:

alert(this.id);
juvian
  • 15,875
  • 2
  • 37
  • 38
2

Demo: http://jsfiddle.net/tzJUN/ using this.id http://jsfiddle.net/c65x9/

If you keen : jQuery attr vs prop?

Stop propogation will stop the click event the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.

API:

Code

$(document).ready(function () {

    $('.click').click(function (event) {
        event.stopPropagation();
        alert($(this).prop("id")); //<< --- or this.id

    });

});
Community
  • 1
  • 1
Tats_innit
  • 33,991
  • 10
  • 71
  • 77
0
$('.click').click(function(e){ 
    $(this).attr("id"); 
alert($(this).attr("id"));//here you can see your clicked id

})
user3386790
  • 156
  • 4
  • 16
0

Yes. its simple

$(document).ready(function(){
$('.click').click(function(){
var ID=$(this).attr('id');
alert(ID);
//This ID varible will return ID of the Div Clicked
});
});
Harjeet Singh
  • 388
  • 2
  • 6
  • 22