如何检查一个元素是否存在于另一个元素中? [英] How to check if an element exist into another element?

查看:114
本文介绍了如何检查一个元素是否存在于另一个元素中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于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:

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

当然可以进一步扩展该插件,使其更加精美(一次处理多个调用,基于pram创建不存在的元素),但是就目前而言,它执行了一个非常简单,非常需要的功能. ..这个元素存在吗?返回TrueFalse

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

这篇关于如何检查一个元素是否存在于另一个元素中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆