3

I have a function that has the signature of:

function(id,target){
 //do stuff
}

The target parameter is assumed to be a jQuery wrapped object however it is possible that it could be a dom element in which case I'd like to wrap it in jQuery before I do operations on it. How can I test the target variable for jQuery?

bittersweetryan
  • 3,383
  • 5
  • 28
  • 42
  • 1
    possible duplicate of [Check if object is a jQuery object](http://stackoverflow.com/questions/1853223/check-if-object-is-a-jquery-object) – Richard Ev Oct 04 '11 at 15:35
  • you can also check the length of the variable. if it has a length defined as 0 then it's jquery. if the length is undefined then it's dom. – scrappedcola Oct 04 '11 at 15:35
  • 1
    @scrappedcola Probably a bad idea, as arrays are not jQuery objects. – Andrew Oct 04 '11 at 15:37
  • Richard, thanks for pointing that out. When I did my initial research I used "variable" in my search which didn't turn up any relevant results. – bittersweetryan Oct 04 '11 at 15:38

2 Answers2

3

You can use instanceof

obj instanceof jQuery

Check if object is a jQuery object

Community
  • 1
  • 1
aziz punjani
  • 25,586
  • 9
  • 47
  • 56
3
if(!(target instanceof jQuery)) {
  target = jQuery(target);
} 
John Strickler
  • 25,151
  • 4
  • 52
  • 68