Unless you have another way to identify <div> elements, this places a handler on each <div> on the page.
$('div').click(function() { var text = $(this).text();
The .text() method returns the text content for this <div> (as well as any nested elements).
If you only need the click event for specific <div> elements, it is best to add a class and choose the right ones based on this.
$('div.myClass').click(function() { var text = $(this).text();
HTML
<div class="myClass">'.$i.'</div> <div class="myClass">'.$i.'</div> <div class="myClass">'.$i.'</div> <div>some other div</div>
If the <div> elements are within the same ancestor element, you can instead use .delegate() , in which one ancestor handler will be placed to handle all divs inside.
$('#parentID').delegate('div.myClass', 'click', function() { var text = $(this).text();
HTML
<div id="parentID"> <div class="myClass">'.$i.'</div> <div class="myClass">'.$i.'</div> <div class="myClass">'.$i.'</div> </div>
(Requires jQuery 1.4 or later)
user113716
source share