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

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

有些人喜欢:

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

如果.search_element进入#container ,则必须返回YES,否则返回NO。

我该怎么做? 尝试使用$ .contains(’#container’,’。search_element’),但似乎这个函数不起作用……


¡¡¡更新!

请参阅我的回答[ 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

一个简单的长度检查:

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

你可以使用.is:has ,只是为了完整。 我更喜欢测试.length的解决方案。

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

检查数组的长度

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

jQuery有一个默认方法:

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

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