348

In jQuery, if I have a reference to an element, how can I determine what kind of element it is, for example, an input or an dropdown? Is there any way to find out?

Duplicate:

How can I determine the element type of a matched element in jQuery?

Community
  • 1
  • 1
jyotishka bora
  • 3,963
  • 2
  • 23
  • 19
  • 5
    Duplicate: http://stackoverflow.com/questions/341900/how-can-i-determine-the-element-type-of-a-matched-element-in-jquery – Ólafur Waage Mar 03 '09 at 22:06
  • 10
    May be a duplicate, but it has a better answer, and the other one is tagged badly. – Rumpleteaser Sep 20 '12 at 21:41
  • 2
    @Rumpleteaser If "the other one" is tagged badly, then why don't you make use of `edit` button below it and tag it perfectly? – trejder Apr 16 '15 at 07:45

3 Answers3

618

The following will return true if the element is an input:

$("#elementId").is("input") 

or you can use the following to get the name of the tag:

$("#elementId").get(0).tagName
Marius
  • 57,995
  • 32
  • 132
  • 151
  • 59
    When using $("#elementId").get(0).tagName the tagName will be in all caps - TR, DIV etc etc – Jarede Oct 18 '12 at 14:41
  • 7
    okay, so the tagName property returns an all caps value, I just did a `.toLowerCase()` on it – pythonian29033 Aug 15 '13 at 12:15
  • 9
    `var elementType = $(this).prop('tagName');` – Damodar Bashyal May 09 '14 at 00:58
  • 5
    Using `nodeName` might be more consistent across different browsers: http://stackoverflow.com/questions/4878484/difference-between-tagname-and-nodename – Nathan Jones Jun 02 '14 at 18:12
  • 2
    Note, that using `$("#elementId").is(":input")` will generally tell you, if you're dealing with any kind of form element, without checking for its specific type ([reference](http://stackoverflow.com/a/11689147/1469208)). – trejder Apr 16 '15 at 08:11
14

You can use .prop() with tagName as the name of the property that you want to get:

$("#elementId").prop('tagName'); 
Resolution
  • 759
  • 1
  • 7
  • 18
4

It is worth noting that @Marius's second answer could be used as pure Javascript solution.

document.getElementById('elementId').tagName
Matas Vaitkevicius
  • 58,075
  • 31
  • 238
  • 265