jQuery Plugin: Element Existence

Just a Quick little snippet really..

Over at JqueryForDesigners.com @rem mentioned about checking if an element exists or not, I’ve been doing this for some time using the following snippet:

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

to use it you can now do this:

if ($('#elem').exists()) { /* do something */ }

Hope this is helpful to some people

One comment

  1. Abro says:

    hummm … i don’t think it’s that this makes a lot of sense,
    since we should just do this:
    if ( $('#elem').length )
    or this
    if ( !$('#elem').length )
    but i did similar things some time ago (slooow things ;O)
    and i understand that jquery isn’t really associative.

    just go on with that, i like your way of thinking.

Leave a Reply

Your email address will not be published. Required fields are marked *

*