I have a series of divs with the class "addedelement" which are dynamically added. Inside all of this layers there are more nested divs, one of them containing some images with attached events. When I click on one of this images I want to know if it is inside the LAST of those divs:
if($(this).is('div.addedelement:last div.contextmenu img.up'))
{
alert('Ok');
}
I don't know why, but this conditional expression is fired independently of the case in which the trigger is inside the last 'elementadded' div or not. But if I try to apply a css to the element like this:
$('div.addedelement:last div.contextmenu img.up').css('display','none');
It works like a charm. What I'm missing? Can anybody help me?
One option is using jQuery index
method, you can select the closest parent of the image with class of .addedelement
and pass the element to the index
method, if the length of the cached jQuery object(-1) equals to the index of the parent element within jQuery collection then the element is the last one.
// define these variables outside of the event handler
var $a = $('div.addedelement'), len = $a.length - 1;
// within your event handler
var cur = $(this).closest('div.addedelement').get(0);
if ( $a.index(cur) === len ) {
// last
}
However. if you want to register a handler only for the images within the last div element with class of addedelement
you can code:
$('div.addedelement').last().find('img.up').click(function(){
// last
})