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.
contains() method checks if an element is inside another, and returns a boolean: true if it is, and false if it's not. Call it on the parent element, and pass the element you want to check for in as an argument.
A descendant is an element that is nested inside another element.
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 )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With