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.
Paolo Bergantino May 14, '09 at 20:23 2009-05-14 20:23
source share