如何检查一个元素是否存在于另一个元素中?
对于jQuery,我想了解一个元素是否存在于另一个元素中.
I'd like, to jQuery, understand if an element exist into another element.
类似的东西:
if($('#container').find('.search_element'))
如果.search_element
放入#container
,
必须返回YES,否则返回NO.
must return YES if .search_element
is into #container
, NO otherwise.
我该怎么办?尝试使用$ .contains('#container','.search_element'),但此功能似乎无效...
How can I do it? Tried with $.contains('#container', '.search_element') but seems that this function doesnt works...
¡¡¡UPDATE !!!
查看我的答案 [" HERE ] ,以获得更强大的 插件!
¡¡¡UPDATE!!!
See my answer [ HERE ] for a MUCH more robust plugin!
您可以使用以下方法轻松地缩短@Chris的答案:
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:
(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();
当然可以进一步扩展该插件,使其更加精美(一次处理多个调用,基于pram创建不存在的元素),但是就目前而言,它执行了一个非常简单,非常需要的功能. ..这个元素存在吗?返回True
或False
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