0

Suppose I have created one jQuery function to check if elements exist or not like:

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

Then I call:

if ($("#MyDiv").exists() == false)
   alert('not exist');
else
   alert('exist');

If I call jQuery function above it works. But can't we call the jquery function like this way exists('#MyDiv') ? If I try to call this way then I am not getting result...why?

gdoron is supporting Monica
  • 142,542
  • 55
  • 282
  • 355
Thomas
  • 32,301
  • 119
  • 343
  • 612

4 Answers4

2

ARRG, please, don't use this useless exist function!

It can be simply with:

if ($('#MyDiv').length)
    // Exist
else
    // Doesn't exist.

No plugins needed, everyone knows what this code does, Don't use exist.

gen_Eric
  • 214,658
  • 40
  • 293
  • 332
gdoron is supporting Monica
  • 142,542
  • 55
  • 282
  • 355
1

Try like below,

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

and use as,

$.exists('#test') 

DEMO: http://jsfiddle.net/skram/hgaPt/1/

Please use this in a bigger picture, using it for simple thing as exist is just a overkill.

Selvakumar Arumugam
  • 78,145
  • 14
  • 119
  • 133
  • why u did not specify jquery function prototype like jQuery.fn.exists = function () {) rather u wrote code like $.exists = function (selector) {)....both are same? jQuery.fn keyword is optional. please discuss – Thomas Jun 20 '12 at 07:01
0
exists('#MyDiv')

This won't work because you didn't make a function called exists. You made a function called jQuery.fn.exists (jQuery.fn is the prototype of jQuery objects).

For exists('#MyDiv') to work, you need to make a function called exists.

function exists(sel){
    return $(sel).length;
}
gen_Eric
  • 214,658
  • 40
  • 293
  • 332
0

$.fn is equal to $.prototype, so indirectly using $.fn you are hooking your functions to jQuery object prototype, so the selector needs to be passed to the jQuery object not the chained function name.

gen_Eric
  • 214,658
  • 40
  • 293
  • 332
Ajay Beniwal
  • 18,447
  • 8
  • 74
  • 93