Reputation: 6916
I want to create function that can be used either with Id or by passing jQuery object.
var $myVar = $('#myId');
myFunc($myVar);
myFunc('myId');
function myFunc(value)
{
// check if value is jQuery or string
}
How can I detect what kind of argument was passed to the function?
Note! This question is not same. I don't want to pass selector string like #id.myClass
. I want to pass the jQuery object like in the example.
Upvotes: 10
Views: 8240
Reputation: 4453
function myFunc(value)
{
if(typeof(value) == 'string')
//this is a string
else if (value === jQuery)
//this is jQuery
else if (typeof(value) == 'object')
//this is an object
}
NOTE: did this in the console:
> jQuery
function (a,b){return new e.fn.init(a,b,h)}
> var value = jQuery
undefined
> value
function (a,b){return new e.fn.init(a,b,h)}
> value === jQuery
true
Upvotes: 0
Reputation: 11633
function myFunc(value)
{
if (typeof value == "string") {
//it's a string
}
else if (value != null && typeof value == "object"} {
//it's an object (presumably jQuery object)
}
else {
//it's null or something else
}
}
Upvotes: 1
Reputation: 5077
Try using typeof, eg:
var $myVar = $('#myId');
myFunc($myVar);
myFunc('myId');
function myFunc( value ){
// check if value is jQuery or string
switch( typeof value ) {
case 'object':
// is object
break;
case 'string':
// is string
break;
// etc etc.
}
}
Upvotes: 0
Reputation: 5475
Every jquery object has a property jquery
. This will fail, of course, if your object has jquery
property...but you can have stricter checking if you want...
function(o) {
if(typeof o == 'object' && o.jquery) // it's jquery object.
}
Upvotes: 3
Reputation: 291
Try this:
function myFunc(value)
{
if(typeof value === 'object') {
}
else{
}
}
Upvotes: 0
Reputation: 53228
Would it not be sufficient to check the type of the argument?
function myfunc(arg)
{
if(typeof arg == 'string')
{
}
else if(typeof arg == 'object')
{
}
}
Check this Fiddle.
Upvotes: 0
Reputation: 74076
Use the typeof
operator
if ( typeof value === 'string' ) {
// it's a string
} else {
// it's something else
}
Or to make really sure it's an instance of the jQuery object
if ( typeof value === 'string' ) {
// it's a string
} else if ( value instanceof $) {
// it's a jQuery object
} else {
// something unwanted
}
Upvotes: 18