开发者

How to know the type of an jQuery object?

开发者 https://www.devze.com 2022-12-13 16:25 出处:网络
I need to detect whet开发者_如何学Cher it\'s a <option> or something elseYou can use the is method to check whether a jQuery object matches a selector.

I need to detect whet开发者_如何学Cher it's a <option> or something else


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

For example:

var isOption = someObj.is('option');


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).


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
}
0

精彩评论

暂无评论...
验证码 换一张
取 消