views:

268

answers:

3

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.

+1  A: 

There's nothing built in that will give you the result you're looking for. The easiest way is going to be to roll your own function.

...could always make it your own extension. I know I've had to do the same thing several times in the past.

Justin Niessner
+7  A: 

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.

Paolo Bergantino
+1  A: 

if you know the id of the grand-parent container, you can just write a recursive function that says (I don't recall the actual syntax, but it's close to this...)

function findAncestorById(id){
    if(this.parentNode){
       if(this.parentNode.id == id)
          return this.parentNode
       else
           return this.parentNode.findAncestorById(id); 
     }
    return null;
}

div._prototype.findAncestorById = findAncestoryById;

something along those lines...

Dr.Dredel
Yup i know that that's why i asked "a direct way"
fmsf
if by "direct way" you mean a reserved method, inside the javascript library, then as far as I know, the answer is no. However, the above is a fairly simple solution :)
Dr.Dredel