Why does $('#id') return true if id doesn't exist?

前端 未结 6 704
野趣味
野趣味 2020-11-28 13:08

I always wondered why jQuery returns true if I\'m trying to find elements by id selector that doesnt exist in the DOM structure.

Like this:

6条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-28 14:03

    It returns true because to Javascript it is a defined object therefore not false, and jQuery will always give you a new object regardless of whether the element is found or not - however the array length will be zero, e.g.

    $("span").length

    If you have no , this will be zero, but it could be 1 or more.

    You can write your own plugin to avoid repeated if statements as a Jquery plugin, like I did for this one. It's fairly easy to do:

    (function($)
    {
            /* Checks if a jQuery object exists in the DOM, by checking the length of its child elements. */
            $.fn.elementExists = function()
            {
                    ///     
                    ///     Checks if a jQuery object exists in the DOM, by checking the length of its child elements.
                    ///     
                    ///     
                    return jQuery(this).length > 0;
            };
    })(jQuery);
    

    Usage:

    if ($("#someid").elementExists())
    {
    
    }
    

提交回复
热议问题