17

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

markzzz
  • 47,390
  • 120
  • 299
  • 507

5 Answers5

20

A simple length check:

if($("#container").find(".search_element").length) {
    // If the length is greater than 0, it exists
} else {
    // else, false
}
Chris
  • 3,729
  • 22
  • 30
15

¡¡¡UPDATE!!!

See my answer [ HERE ] for a MUCH more robust plugin!


You could easily shorten @Chris answer with:

if($("#container .search_element").length) { ...

You could also do the same with a useful plugin i made for this:

jsFiddle

(function($) {
    if (!$.exist) {
        $.extend({
            exist: function(elm) {
                if (typeof elm == null) return false;
                if (typeof elm != "object") elm = $(elm);
                return elm.length ? true : false;
            }
        });
        $.fn.extend({
            exist: function() {
                return $.exist($(this));
            }
        });
    }
})(jQuery);

USE

//  With your if statement
if($("#container .search_element").exist()) { ...

//  With ID 
$.exist("#eleID");
//  OR
$("#eleID").exist();

//  With class name
$.exist(".class-name");
//  OR
$(".class-name").exist();

//  With just tag // prolly not best idea aS there will be other tags on site
$.exist("div");
//  OR
$("div").exist();

Of course this plugin could be further extended to be much more fancy (handling multiple calls at once, creating non-existing elements based on a pram), but as it stand now, it does a very simple, very needed function ... Does this element exist? return True or False

jsFiddle

Community
  • 1
  • 1
SpYk3HH
  • 22,272
  • 11
  • 70
  • 81
  • Tip (i'm thinking of doing this anyway, but not sure its how people will want to use it) you could edit the plugin to have a callback function. Then you wouldn't need the "if" statement at all. – SpYk3HH Sep 17 '13 at 15:46
3

You can use .is and :has, just to be complete. I would prefer a solution which tests .length though.

if($('#container').is(':has(.search_element)')) {
   // I haz that
}
karim79
  • 339,989
  • 67
  • 413
  • 406
2

check the length of the array

if($('#container').find('.search_element').length)
red-X
  • 5,108
  • 1
  • 25
  • 38
1

jQuery has a default method for this:

$("#container").has(".selector");

http://api.jquery.com/has/

Flexo
  • 87,323
  • 22
  • 191
  • 272
Roi
  • 1,597
  • 16
  • 19