Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know the type of an jQuery object?

Tags:

jquery

I need to detect whether it's a <option> or something else

like image 440
user198729 Avatar asked Dec 08 '09 02:12

user198729


People also ask

What is Typeof in jQuery?

The typeof operator when applied to the jQuery object returns the string "function" . Basically that does mean that jQuery is a function.

How can I tell if an object is a jQuery object?

Check out the instanceof operator. Show activity on this post. The best way to check the instance of an object is through instanceof operator or with the method isPrototypeOf() which inspects if the prototype of an object is in another object's prototype chain.

What does $() mean in jQuery?

In jQuery, the $ sign is just an alias to jQuery() , then an alias for a function. This page reports: Basic syntax is: $(selector).action() A dollar sign to define jQuery.


3 Answers

You can use the is method to check whether a jQuery object matches a selector.

For example:

var isOption = someObj.is('option');
like image 107
SLaks Avatar answered Oct 06 '22 06:10

SLaks


Try this:

yourObject[0].tagName;

Since a jQuery object is an array of objects you can retrieve the underlying DOM element by indexing that array. Once you have the element you can retrieve its tagName. (Note that even if you have one element you will still have an array, albeit an array of one element).

like image 28
Andrew Hare Avatar answered Oct 06 '22 06:10

Andrew Hare


You should be able to check the .nodeName property of the element. Something about like this should work for you:

// a very quick little helper function
$.fn.getNodeName = function() { 
  // returns the nodeName of the first matched element, or ""
  return this[0] ? this[0].nodeName : "";
};

var $something = $(".something");

alert($something.getNodeName());

I generally prefer using jQuery's .is() to test what something is.

Checks the current selection against an expression and returns true, if at least one element of the selection fits the given expression.

if ($something.is("option")) {
  // work with an option element
}
like image 41
gnarf Avatar answered Oct 06 '22 06:10

gnarf