How can I check if an element is inside another in jQuery?

Is there any direct way in JavaScript or jQuery to check if an element is inside another.

I do not mean $(this).parent , since the element I want to find may be a random number step below in the element tree.

As an example, I would like to check if < div id="THIS DIV"> is within < div id="THIS PARENT"> :

 <div id="THIS_PARENT"> <div id="random"> <div id="random"> <div id="random"> <div id="THIS_DIV"> (... close all divs ...) 

So in the pseudo code:

  if($("div#THIS_DIV").isWithin("div#THIS_PARENT")) ... 

If there is no direct way, I will probably make a function for this, but it's still worth asking for it.

+24
javascript jquery
May 14, '09 at 20:15
source share
2 answers

You can do it:

 if($('#THIS_DIV','#THIS_PARENT').length == 1) { } 

specifying the context for the search (second argument), we basically say: "Look for the element with the identifier #THIS_DIV inside the element with the identifier #THIS_PARENT ". This is the most succint way to do this using jQuery.

We could write it like this using find , if that makes more sense to you:

 if($('#THIS_PARENT').find('#THIS_DIV').length == 1) { } 

Or, for example, using parents if you want to search from the child up:

 if($('#THIS_DIV').parents('#THIS_PARENT').length == 1) { } 

Any of these should work fine. The length bit is needed to ensure that the length of the “search” is> 0. Of course, I personally recommend that you go to the first one, since this is the easiest.

In addition, if you reference an element by identifier, it is not needed (although, of course, excellent), so that the preface of the selector with the tag name is used. Regarding speed, however, this doesn’t help much since jQuery is going to use the built-in getElementById() inside. Using a tag name is only important when choosing by class, because div.myclass much, much faster than .myclass if only the <div> elements will have a specific class.

+42
May 14, '09 at 20:23
source share

With jQuery> = 1.4 (2010) you can use the very fast jQuery.contains () function

This static method works with DOM elements, not jQuery elements, and returns true or false .

 jQuery.contains( container, descendant ) 

Example. To check if an element is in the document, you can do this:

 jQuery.contains( document.body, myElement ) 
+16
Apr 09 '13 at 21:40
source share



All Articles