I'd like, to jQuery, understand if an element exist into another element.
Somethings like :
if($('#container').find('.search_element'))
must return YES if .search_element
is into #container
, NO otherwise.
How can I do it? Tried with $.contains('#container', '.search_element') but seems that this function doesnt works...
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.
Approach 1: First, we will use document. getElementById() to get the ID and store the ID into a variable. Then compare the element (variable that store ID) with 'null' and identify whether the element exists or not.
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. Any of these should work fine.
A simple length check:
if($("#container").find(".search_element").length) {
// If the length is greater than 0, it exists
} else {
// else, false
}
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