tags:

views:

40

answers:

3

Hi

i have three divs like that:

<div id="1" >id="1"</div>
<div id="2">id="2"</div>
<div id="3">id="3"</div>

Now i want, when i click any of the div, jquery will get it id, i.e, if i click div 1, it will get 1 as its div id is 1.

any help will be great.

regards

+5  A: 
$(function() {
    $('div').click(function() { alert($(this).attr('id')); });
});

or shorter:

$(function() {
    $('div').click(function() { alert(this.id); });
});
Yuriy Faktorovich
Thanks Yuriy Faktorovich,thanks a lot
TIT
+4  A: 
$("div").click(function() {
    var eleId = $(this).attr("id");
}
Metropolis
+2  A: 

You can either use delegation or assign a click-handler to each of the divs:

$('#1, #2, #3').click(
   function (e) {
      alert($(this).attr('id') + ' was clicked');
   }
)

If you have a parent container you could use the live-method to bind a single listener and utilize event delegation:

<div id="parent">
   <div id="1" >id="1"</div>
   <div id="2">id="2"</div>
   <div id="3">id="3"</div>
</div>

$('#parent > div').live('click', function (e) {
   alert($(this).attr('id') + ' was clicked');
});
PatrikAkerstrand