Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect is argument jQuery object

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.

like image 488
Tx3 Avatar asked May 23 '12 13:05

Tx3


People also ask

How do you check if a function is called in jQuery?

This post shows how to check if a function exists, before calling it. We will use both JavaScript as well as jQuery (JavaScript library) to do so. jQuery contains the jQuery. isFunction() which finds out if the parameter passed to it is a function.

What is $( this in jQuery?

$(this) is a jQuery wrapper around that element that enables usage of jQuery methods. jQuery calls the callback using apply() to bind this . Calling jQuery a second time (which is a mistake) on the result of $(this) returns an new jQuery object based on the same selector as the first one.

How do I know which DIV is clicked?

To check if an element was clicked, add a click event listener to the element, e.g. button. addEventListener('click', function handleClick() {}) . The click event is dispatched every time the element is clicked.


1 Answers

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
   }


}
like image 161
Marc Avatar answered Sep 23 '22 22:09

Marc