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
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.
With jQuery >=1.4 (2010) you can use the very fast function jQuery.contains()
This static method works with DOM elements, not with jQuery elements and returns true
or false
.
jQuery.contains( container, descendant )
Example: To check if a element is in the document you could do this:
jQuery.contains( document.body, myElement )