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!
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!
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.
You can test the tag name this way :
jQuery('#urDivId').parent().is('body')
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.
if ( $(this).parent()[0].nodeName.toLowerCase() == "body" )
{
// do stuff here
}
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);