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

javascript, jquery

Solution

You could do this:

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

}

By specifying a context for the search (the second argument) we are basically saying "look for an element with an ID of `#THIS_DIV` within an element with ID of `#THIS_PARENT`". This is the most succint way of doing it using jQuery.

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

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

}

Or like this, using `parents`, if you want to search from the child upwards:

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

}    

Any of these should work fine. The `length` bit is necessary to make sure the length of the "search" is > 0. I would of course personally recommend you go with the first one as it's the simplest.

Also, if you are referring to an element by ID it's not necessary (although of course perfectly okay) to preface the selector with the tag name. As far as speed, though, it doesn't really help as jQuery is going to use the native `getElementById()` internally. Using the tag name is only important when selecting by class, as `div.myclass` is much, much faster than `.myclass` if only `<div>` elements are going to have the particular class.

Problem

Is there any direct way in JavaScript or jQuery to check if an element is within another one. I'm not referring to the `$(this).parent` as the element I wish to find can be a random number steps lower in the tree of elements. As an example, I would like to check if `< div id="THIS DIV">` would be 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 pseudo code: ``` if($("div#THIS_DIV").isWithin("div#THIS_PARENT")) ... ``` If there isn't any direct way I'll probably do a function for this but still it's worth asking.

Original source