Reputation: 509
I have made a dynamic system so you can append divs in divs in divs etc. Now I want to know the id of the div when I click on it. I have made a script like this: HTML:
<div id="div1" class="mod">
<div id="div4" class="mod">
<div id="div5" class="mod"></div>
</div>
</div>
<div id="div2" class="mod">
<div id="div6" class="mod">
<div id="div7" class="mod"></div>
</div>
</div>
Jquery:
$('.mod').click(function(){
var id = $(this).attr('id');
alert(id);
});
If you click for example on div4 it will return div_4 and div_1 but I only want div_4 as return. Can someone help me? I read something about parents and children but I can't figure it out. Regards Frank
Upvotes: 1
Views: 1804
Reputation: 901
You can stop the bubbling of the event with:
$('.mod').click(function(event){
var id = $(this).attr('id');
alert(id);
event.stopPropagation();
});
The click-event then should only reach the highest layer/div.
Upvotes: 4
Reputation: 1
Don't add click events to every element. Add one click event to the container of all of the divs, and then use the jquery event object to get the target element that was clicked.
Upvotes: 0