Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if an element exist into another element?

Tags:

jquery

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...

like image 233
markzzz Avatar asked Aug 24 '11 10:08

markzzz


People also ask

How do you check an element is inside an element?

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.

How do you find if element with specific ID exists or not?

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.

How do you check if an element is inside a div jQuery?

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.


1 Answers

A simple length check:

if($("#container").find(".search_element").length) {
    // If the length is greater than 0, it exists
} else {
    // else, false
}
like image 96
Chris Avatar answered Oct 07 '22 00:10

Chris