如何检查元素是否存在于另一个元素中?

时间:2011-08-24 10:41:28

标签: jquery

我想,对于jQuery,要了解一个元素是否存在于另一个元素中。

某些事情如:

if($('#container').find('.search_element'))
如果.search_element进入#container

必须返回YES,否则返回NO。

我该怎么办?尝试使用$ .contains('#container','。search_element')但看起来这个函数不起作用......

5 个答案:

答案 0 :(得分:19)

简单的长度检查:

if($("#container").find(".search_element").length) {
    // If the length is greater than 0, it exists
} else {
    // else, false
}

答案 1 :(得分:11)


¡¡¡UPDATE !!!

有关 MUCH 更强大的插件,请参阅我的回答 [ HERE ]


您可以通过以下方式轻松缩短@Chris答案:

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

您也可以使用我为此制作的有用插件执行相同的操作:

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);
  

使用

//  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();

当然这个插件可以进一步扩展到更加花哨(一次处理多个调用,根据婴儿车创建不存在的元素),但是就目前而言,它做了一个非常简单,非常需要的功能。 ..这个元素存在吗?返回TrueFalse

jsFiddle

答案 2 :(得分:3)

您可以使用.is:has来完成。我更喜欢测试.length的解决方案。

if($('#container').is(':has(.search_element)')) {
   // I haz that
}

答案 3 :(得分:1)

检查数组的长度

if($('#container').find('.search_element').length)

答案 4 :(得分:1)

jQuery有一个默认方法:

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

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