How to check if an element exist into another elem

2020-06-02 00:07发布

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

标签: jquery
5条回答
祖国的老花朵
2楼-- · 2020-06-02 00:38

check the length of the array

if($('#container').find('.search_element').length)
查看更多
▲ chillily
3楼-- · 2020-06-02 00:42

jQuery has a default method for this:

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

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

查看更多
Anthone
4楼-- · 2020-06-02 00:45

A simple length check:

if($("#container").find(".search_element").length) {
    // If the length is greater than 0, it exists
} else {
    // else, false
}
查看更多
够拽才男人
5楼-- · 2020-06-02 00:46

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

查看更多
欢心
6楼-- · 2020-06-02 00:46

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
}
查看更多
登录 后发表回答