How to find out if an element is a direct child of a body using jQuery

I want to perform some actions on elements that are not a direct child of the body. How can I check a specific element to find out if its composition is part of the body.

Thanks!

+4
source share
5 answers

You can check the tag name this way:

jQuery('#urDivId').parent().is('body') 
+11
source

> denotes a direct child. $('body > *') gives you all the children of the body tag, so you can always invert this with :not( ) : $('*:not(body > *)') ; however, this can be rather slow.

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

Any of the above should provide you with a complete set of all elements that are not children of the body tag.

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

+3
source

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

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

Lots of good answers. If you are interested in chaining, here is another possibility that uses parent () and : 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); 
0
source

Source: https://habr.com/ru/post/1312083/


All Articles