views:

46

answers:

5

I want to perform some action on elements that are not direct child of the body. How can I check a particular element to know whether its partent is the body.

Thanks!

+2  A: 

simply you can use the parent function jquery('#yourElement').parent(); if it gives you body tag than you can find that its direct child of body.

sushil bharwani
It's `jQuery`, with a capital `Q`. ;-)
Tomalak
+3  A: 

You can test the tag name this way :

jQuery('#urDivId').parent().is('body')
greg0ire
+1  A: 

The > denotes a direct child. $('body > *') gives you all children of the body tag, so you could always invert that with a :not( ): $('*:not(body > *)'); however that might be pretty slow.

filter( ) would also work for you and may be faster: $('body *').filter(function(){ return $(this).parent('body') });

Either of the above should give you a complete set of all elements that are not children of the body tag.

Note that there could potentially be a huge number of elements selected here; you will want to make your selectors as specific as possible for performance and you should probably avoid wildcards, which I used for the sake of the examples above.

ajm
+1  A: 
if ( $(this).parent()[0].nodeName.toLowerCase() == "body" ) 
{
// do stuff here
}
Razor
A: 

Lots of good answers. If you are interested in chaining, here is yet another possibility that uses parent() and the :not() selector.

var $possible_targets = [...]; // all the elements you want to check
function do_something_to_target() { 
    [...]; // insert blinking text code here! 
}

$possible_targets.parent(':not(body)').each(do_something_to_target);
istruble