How to know the type of an jQuery object?

2020-07-06 05:46发布

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

标签: jquery
3条回答
聊天终结者
2楼-- · 2020-07-06 05:59

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

查看更多
We Are One
3楼-- · 2020-07-06 06:19

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
}
查看更多
【Aperson】
4楼-- · 2020-07-06 06:24

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

For example:

var isOption = someObj.is('option');
查看更多
登录 后发表回答