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

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.

Leave a Comment