Sunday, May 27, 2012

Is there an "exists' function for jQuery


So I know that you can do:




if ($(selector).length>0) {
// Do something
}



But is there a more elegant method?


Source: Tips4all

14 comments:

  1. Yes!

    jQuery.fn.exists = function(){return this.length>0;}

    if ($(selector).exists()) {
    // Do something
    }


    There you go!

    This is in response to: Herding Code podcast with Jeff Atwood

    ReplyDelete
  2. In JavaScript, everything is truthy or falsy and for numbers, 0 means false, everything else true. So you could write:

    if ($(selector).length)


    and you don't need that "> 0" part.

    ReplyDelete
  3. if you used:

    jQuery.fn.exists = function(){return ($(this).length > 0);}
    if ($(selector).exists()) { }


    you would imply that chaining was possible when it is not.

    This would be better

    jQuery.exists = function(selector) {return ($(selector).length > 0);}
    if ($.exists(selector)) { }


    EDIT

    Just found this in the FAQ:

    http://docs.jquery.com/Frequently_Asked_Questions#How_do_I_test_whether_an_element_exists.3F

    if ( $('#myDiv').length ) { //do something }


    EDIT 2

    you could also use the following. If there are no values in the jQuery obj array then getting the first item in the array would return undefined.

    if ( $('#myDiv')[0] ) { //do something }

    ReplyDelete
  4. you can use this

    // if element exists

    if($('selector').length){ //do something }




    // if element not exists

    if(!$('selector').length){ //do something }

    ReplyDelete
  5. You can use:

    if ($(selector).is('*')) {
    // Do something
    }


    A little more elegant, perhaps.

    ReplyDelete
  6. I have found if ($(selector).length) {} to be insufficient. It will silently break your app when selector is an empty object {}.

    var $target = $({});
    console.log($target, $target.length);

    // Console output:
    // -------------------------------------
    // [▼ Object ] 1
    // ► __proto__: Object


    My only suggestion is to perform an additional check for {}.

    if ($.isEmptyObject(selector) || !$(selector).length) {
    throw new Error('Unable to work with the given selector.');
    }


    I'm still looking for a better solution though as this one is a bit heavy.

    Edit: WARNING! This doesn't work in IE when selector is a string.

    $.isEmptyObject('hello') // FALSE in Chrome and TRUE in IE

    ReplyDelete
  7. if ( $('#myDiv').size() > 0 ) { //do something }


    size() counts the number of elements returned by the selector

    ReplyDelete
  8. I have found that sometimes .length throws an error, but [element locator].size() > 0 works reliably

    ReplyDelete
  9. There's no need for jquery really. With plain JavaScript its easier and semantically correct to check for:

    if(document.getElementById = "myElement") {
    //do something...
    }


    If for any reason you don't want to put an id to the element, you can still use all the other javascript methods designed to access the DOM, such as getElementsByTagName, DOM index, child selector, etc.

    jquery es really cool, but don't let pure js to fall into oblivion...

    ReplyDelete
  10. The fastest and most semantically self explaining way to check for existence is actually by using plain JavaScript:

    if (document.getElementById('element_id')) {
    // Do something
    }


    It is a bit longer to write than the jQuery length alternative, but executes faster since it is a native JS method.

    And it is better than the alternative of writing your own jQuery function. That alternative is slower, for the reasons @snover stated. But it would also give other programmers the impression that the exists() function is something inherent to jQuery. JavaScript would/should be understood by others editing your code, without increased knowledge debt.

    NB: Notice the lack of an '#' before the element_id (since this is plain JS, not jQuery).

    ReplyDelete
  11. I had a case where I wanted to see if an object exists inside of another so I added something to the first answer to check for a selector inside the selector..

    // Checks if an object exists.
    // Usage:
    //
    // $(selector).exists()
    //
    // Or:
    //
    // $(selector).exists(anotherSelector);
    jQuery.fn.exists = function(selector) {
    return selector ? this.find(selector).length : this.length;
    };

    ReplyDelete
  12. you can use jQuery's own "isEmptyObject" : http://api.jquery.com/jQuery.isEmptyObject/

    if(!$.isEmptyObject('selector')) { // Do something }




    Learning by doing... your best option would be what Tim Büthe suggests:

    if ($(selector).length)

    ReplyDelete
  13. You can also run a function only if it exists.

    $.fn.ifExists = function(error, fn) {
    if (this.length) {
    $(fn(this));
    }
    else {
    alert(error);
    }
    };


    Implementation: Hide if it exists

    $("a.next").ifExists( function(t) { t.hide(); } );


    But you don't actually need to do this for hiding because it will return the jquery object either way.

    $.fn.ifExists = function(error, fn) {
    if (this.length) {
    $(fn(this));
    }
    else {
    alert(error);
    }
    };

    $('#button').ifExists("#button does not exits", function(){
    alert("Work");
    });


    great code, added error statement for my own use.

    ReplyDelete
  14. if ($('selector')!=null)
    {
    // Do something
    }


    or shorter...

    if (!!$('selector'))
    {
    // Do something
    }

    ReplyDelete