tags:

views:

74

answers:

5
var target = $(this).attr("href");

if {target is child of ('.wrapper')} then (do something)

simple syntax? can someone show me the correct syntax here?

+6  A: 
if($(target).parents('.wrapper').length > 0) {
   //do something...
}
Jacob Relkin
Small modification instead of $(target) use $(this) as target contains string.
Chinmayee
Note that this tests that target is a direct child of wrapper.
cherouvim
@Chinmayee, the `href` is pointing to the actual `id` of the element that the OP wants to check, not `this`.
Jacob Relkin
This won't work if it's nested two levels down, though.
peirix
@peirix, Now it will.
Jacob Relkin
You should use closest instead of parents.
Ghommey
Better to check `.length > 0`.
rahul
@rahul, Thanks!
Jacob Relkin
@rahul 0 is a falsy value, though, so you don't really need to.
peirix
A: 

you can use parent or parents method like in the links

http://jsfiddle.net/6BX9n/

http://jsfiddle.net/6BX9n/1/

Haim Evgi
+2  A: 

.has() is maybe the mose convenient syntax:

if( $('.wrapper').has($(target)) ) {
     // do something
}

Even more 'powerful' (in terms of performance) is $.contains(). So an ideal algorithm should look like:

var $wrapper =  $('.wrapper'),
    $target  =  $(this).attr('href');

if( $.contains($wrapper[0], $target[0]) ) {
    // do something
}

Reference: .has(), $.contains()

jAndy
A: 

Can't you bind another event?

$('.wrapper *').click(function() {
    // will execute on childrens of .wrapper
});
BrunoLM
+1  A: 

Small change to Jacob's code, if the child is deeper than one level in.

if($(target).parents('.wrapper').length) {
   //do something...
}
Fordi